<?php

namespace App\Services;

use App\DTOs\MissingLivery;
use App\Models\IgnoredMissingLivery;
use App\Models\UserFlight;
use Illuminate\Support\Enumerable;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Collection;

class AdminService
{
    /** @return Collection<int, MissingLivery> */
    function getMissingLiveries(): Collection
    {

        /*        $existingFiles = collect(glob(public_path('img/liveries/generated/*')))
                    ->map(fn ($path) => pathinfo($path, PATHINFO_FILENAME))
                    ->toArray();*/


        $existingFiles = collect(glob(Storage::disk('local')->path('images/liveries').'/*.png'))
            ->map(fn ($path) => pathinfo($path, PATHINFO_FILENAME))
            ->toArray();

        $combos = UserFlight::with(['aircraft', 'airline'])
            ->select('airline_id', 'aircraft_id')
            ->whereNotNull('airline_id')
            ->whereNotNull('aircraft_id')
            ->distinct()
            ->get()
            ->filter(fn ($flight) => $flight->aircraft && $flight->airline)
            ->map(fn ($flight) => [
                'airline_name' => $flight->airline->name,
                'aircraft_display_name' => $flight->aircraft->display_name,
                'filename' => $flight->airline->internal_name . '_' . $flight->aircraft->designator,
                'clipboard_text' => $flight->airline->name . ' ' . $flight->aircraft->display_name_short,
            ])
            ->filter(fn ($combo) => !in_array($combo['filename'], $existingFiles));

        $ignoredFiles = IgnoredMissingLivery::whereIn('filename', $combos->pluck('filename'))->pluck('filename')->toArray();

        return $combos
            ->filter(fn ($combo) => !in_array($combo['filename'], $ignoredFiles))
            ->sortBy('airline_name')
            ->values();
    }

    function getMissingAirlines(): Enumerable|Collection
    {
        $flights = UserFlight::whereNotNull('flight_number')
            ->whereNull('airline_id')
            ->with('user:id,name') // adjust to your actual user relation/columns
            ->get(['id', 'flight_number', 'user_id']);

        return $flights
            ->map(function ($flight) {
                // Extract the 2-character IATA-style prefix (letters and/or digits)
                preg_match('/^([A-Za-z0-9]{2})\d+/', trim($flight->flight_number), $matches);

                return [
                    'code' => $matches[1] ?? null,
                    'flight_number' => $flight->flight_number,
                    'link' => "/u/{$flight->user->name}/flight/{$flight->id}",
                ];
            })
            ->filter(fn ($f) => $f['code'] !== null) // drop any that didn't match the pattern
            ->groupBy('code')
            ->map(function ($group, $code) {
                return [
                    'code' => $code,
                    'flights' => $group->map(fn ($f) => [
                        'flight_number' => $f['flight_number'],
                        'link' => $f['link'],
                    ])->values()->all(),
                ];
            })
            ->values();
    }
}
