<?php

namespace App\DTOs;

use Carbon\Carbon;

readonly class FlightStatData
{
    public function __construct(
        public ?string $aircraft_registration,
        public ?Carbon $estimated_departure_utc,
        public ?Carbon $estimated_arrival_utc,
        public ?Carbon $scheduled_departure_local,
        public ?Carbon $scheduled_arrival_local,
        public ?string $equipment_iata,
        public ?string $departure_iata,
        public ?string $arrival_iata,
        public array   $airline_fs_codes,
        public ?string $operating_fs,
    ) {}

    public static function fromApiResponse(array $flightData): self
    {
        $primaryFs      = $flightData['resultHeader']['carrier']['fs'] ?? null;
        $operatingFs    = $flightData['positional']['flexTrack']['carrierFsCode'] ?? null;
        $codeshares     = array_column($flightData['codeshares'] ?? [], 'fs');

        $fsCodes = array_values(array_unique(array_filter([
            $primaryFs,
            $operatingFs,
            ...$codeshares,
        ])));

        $departureTimezone = $flightData['departureAirport']['timeZoneRegionName'] ?? null;
        $arrivalTimezone   = $flightData['arrivalAirport']['timeZoneRegionName'] ?? null;

        $scheduledDepartureLocal = isset($flightData['schedule']['scheduledDeparture'], $departureTimezone)
            ? Carbon::parse($flightData['schedule']['scheduledDeparture'], $departureTimezone)
            : null;

        $scheduledArrivalLocal = isset($flightData['schedule']['scheduledArrival'], $arrivalTimezone)
            ? Carbon::parse($flightData['schedule']['scheduledArrival'], $arrivalTimezone)
            : null;

        return new self(
            aircraft_registration:  $flightData['positional']['flexTrack']['tailNumber'] ?? null,
            estimated_departure_utc: isset($flightData['schedule']['estimatedActualDepartureUTC'])
                ? Carbon::parse($flightData['schedule']['estimatedActualDepartureUTC'])
                : null,
            estimated_arrival_utc:   isset($flightData['schedule']['estimatedActualArrivalUTC'])
                ? Carbon::parse($flightData['schedule']['estimatedActualArrivalUTC'])
                : null,
            scheduled_departure_local: $scheduledDepartureLocal,
            scheduled_arrival_local:   $scheduledArrivalLocal,
            equipment_iata:         $flightData['additionalFlightInfo']['equipment']['iata'] ?? null,
            departure_iata:         $flightData['departureAirport']['iata'] ?? null,
            arrival_iata:           $flightData['arrivalAirport']['iata'] ?? null,
            airline_fs_codes:       $fsCodes,
            operating_fs: $flightData['positional']['flexTrack']['carrierFsCode'] ?? null,
        );
    }
}
