<?php

namespace App\Http\Resources;

use App\Contracts\Resource;
use App\Http\Resources\SimBriefResource as SimbriefResource;
use App\Models\Flight;
use App\Support\Units\Distance;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Override;
use stdClass;

/**
 * @mixin Flight
 */
class FlightResource extends Resource
{
    /**
     * Set the fields on the flight object
     */
    protected function setFields(): stdClass
    {
        $return_values = new stdClass();
        /** @var Collection $field_values */
        $field_values = $this->field_values;
        if ($field_values->isEmpty() || $field_values->count() === 0) {
            return $return_values;
        }

        foreach ($field_values as $field) {
            $return_values->{$field->name} = $field->value;
        }

        return $return_values;
    }

    /**
     * @throws Exception
     */
    #[Override]
    public function toArray(Request $request): array
    {
        $res = parent::toArray($request);

        // Backwards-compat alias: 'active' mirrors 'enabled' for existing API consumers.
        $res['active'] = $res['enabled'] ?? null;

        // Expose both the structured TIME columns (canonical `H:i:s` strings)
        // and the legacy `Hi`-formatted aliases consumed by ACARS clients and
        // third-party integrations. The legacy keys are projected here rather
        // than via a model accessor so the model stays free of API concerns.
        $res['departure_time'] = $this->departure_time?->format('H:i:s');
        $res['arrival_time'] = $this->arrival_time?->format('H:i:s');
        $res['dpt_time'] = $this->departure_time?->format('Hi');
        $res['arr_time'] = $this->arrival_time?->format('Hi');

        // Display flight callsign if pilot ident usage is not forced by VA
        // Check if there is a callsign too
        if (!empty($this->callsign) && !setting('simbrief.callsign', true)) {
            $res['ident'] = $this->atc.' | '.$this->ident;
        } else {
            $res['ident'] = $this->ident;
        }

        if (empty($res['load_factor'])) {
            $res['load_factor'] = setting('flights.default_load_factor');
        }

        if (empty($res['load_factor_variance'])) {
            $res['load_factor_variance'] = setting('flights.load_factor_variance');
        }

        $distance = Distance::make($res['distance'], config('phpvms.internal_units.distance'));
        $res['distance'] = $distance->getResponseUnits();

        $res['airline'] = new AirlineResource($this->airline);
        $res['subfleets'] = SubfleetResource::collection($this->whenLoaded('subfleets'));
        $res['fields'] = $this->setFields();

        // Simbrief info
        $res['simbrief'] = new SimbriefResource($this->whenLoaded('simbrief'));

        return $res;
    }
}
