<?php

namespace App\Http\Controllers;

use App\Models\UserAction;
use App\Models\UserFlight;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Inertia\Inertia;

class FeedController extends Controller
{
    public function view()
    {
        $user = auth()->user();

        $followeeIds = $user->following()->pluck('followee_id');

        $feed = UserAction::whereIn('user_id', $followeeIds)
            ->whereNotIn('type', ['flight_deleted'])
            ->with([
                'user',
            ])

            ->latest()
            ->limit(50)
            ->get();
        return Inertia::render('Feed', [
            'user' => $user,
            'feed' => $feed,
        ]);
    }

    public function following()
    {
        $user = auth()->user();

        return Cache::remember(
            "user:{$user->id}:following",
            now()->addMinutes(15),
            fn () => $user->following()
                ->with('followee')
                ->get()
                ->pluck('followee')
                ->filter()
                ->values()
                ->toArray()
        );
    }

    public function followingFlights()
    {
        $user = auth()->user();

        return Cache::remember(
            "user_following_flights_{$user->id}",
            now()->addDays(30),
            function () use ($user) {
                $followingIds = $user->following()
                    ->with('followee')
                    ->get()
                    ->pluck('followee')
                    ->filter()
                    ->reject(fn ($followee) => ($followee->settings['profile_privacy'] ?? 'public') === 'private')
                    ->pluck('id');

                return UserFlight::query()
                    ->with(['departureAirport', 'departureAirport.region.country', 'arrivalAirport', 'arrivalAirport.region.country', 'user', 'airline'])
                    ->whereIn('user_id', $followingIds)
                    ->orderByDesc('departure_date')
                    ->limit(100)
                    ->get()
                    ->values()
                    ->toArray();
            }
        );
    }
}
