<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Models\User;
use App\Models\UserFlight;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;

class UserApiController extends ApiController
{
    public function nextFlight(?User $user): JsonResponse
    {
        $user = $user?->exists ? $user : auth()->user();

        if (!$user->id) {
            return response()->json(['message' => 'User not found'], 404);
        }

        if (Gate::denies('viewProfileData', $user)) {
            return response()->json(['message' => 'Cannot access private user.'], 403);
        }

        $flight = UserFlight::with(['departureAirport', 'arrivalAirport', 'airline', 'aircraft'])
            ->where('user_id', $user->id)
            ->where('departure_date', '>', now()->utc())
            ->orderBy('departure_date', 'asc')
            ->first();

        if (!$flight) {
            return response()->json(['message' => 'No upcoming flights found'], 404);
        }

        $departure = Carbon::parse($flight->departure_date)->setTimezone($flight->departureAirport->timezone);
        $arrival = Carbon::parse($flight->arrival_date)->setTimezone($flight->arrivalAirport->timezone);

        return response()->json([
            'departureAirportCode'  => $flight->departureAirport->iata_code,
            'departureCity'         => $flight->departureAirport->municipality,
            'departureDateReadable' => $departure->format('F j'),
            'departureTime'         => $departure->format('H:i'),
            'departureDateUtc'      => $flight->departure_date,
            'arrivalAirportCode'    => $flight->arrivalAirport->iata_code,
            'arrivalCity'           => $flight->arrivalAirport->municipality,
            'arrivalDateReadable'   => $arrival->format('F j'),
            'arrivalTime'           => $arrival->format('H:i'),
            'arrivalDateUtc'      => $flight->arrival_date,
            'flightNumber'          => $flight->flight_number,
            'airlineName'           => $flight->airline?->name,
            'aircraftType'          => $flight->aircraft?->manufacturer_code . ' ' . $flight->aircraft?->model_full_name,
            'logoUrl'               => $flight->airline?->logo_url ?? '',
        ]);
    }

    public function viewableFlights(User $user)
    {
        if (Gate::denies('viewProfileData', $user)) {
            return collect([]);
        }
        return $user->flightsWithRelationshipsLoaded();
    }

    public function viewableDepartedFlights(User $user)
    {
        if (Gate::denies('viewProfileData', $user)) {
            return collect([]);
        }
        return $user->flightsWithRelationshipsLoaded('departed');
    }

}
