<?php

namespace App\Http\Controllers;

use App\Models\Aircraft;
use App\Models\Airline;
use App\Models\Airport;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function airlines(){
        $q = request('q', '');

        return Airline::orderByDesc('active')
            ->where(function ($query) use ($q) {
                $len = strlen($q);
                if ($len === 2) {
                    $query->where('iata_code', 'ilike', $q);
                } elseif ($len === 3) {
                    $query->where('icao_code', 'ilike', $q);
                } else {
                    $query->where('name', 'ilike', "%{$q}%")
                        ->orWhere('iata_code', 'ilike', "%{$q}%")
                        ->orWhere('icao_code', 'ilike', "%{$q}%");
                }
            })
            ->limit(50)
            ->get()
            ->map(fn($airline) => [
                'value' => $airline->id,
                'title' => $airline->display_name,
                'logo_url' => $airline->logo_url,
            ])
            ->values();
    }

    public function aircraft()
    {
        $q = request('q', '');
        $replacedQuery = str_replace(['A3', 'A2'], ['A-3', 'A-2'], $q);

        return Aircraft::where('designator', 'ilike', "%{$q}%")
            ->orWhereRaw("CONCAT(manufacturer_code, ' ', model_full_name) ilike ?", ["%{$q}%"])
            ->orWhereRaw("CONCAT(manufacturer_code, ' ', model_full_name) ilike ?", ["%{$replacedQuery}%"])
            ->limit(200)
            ->orderBy('preferred', 'desc')
            ->get(['id', 'manufacturer_code', 'model_full_name', 'designator'])
            ->map(fn($aircraft) => [
                'value' => $aircraft->id,
                'title' => $aircraft->display_name,
            ])
            ->values();
    }

    public function airports()
    {
        $q = request('q', '');
        $len = strlen($q);

        if ($len < 3) return [];

        return Airport::with('region.country')
            ->when($len === 3, fn($query) => $query->where('iata_code', 'ilike', $q))
            ->when($len >= 4, fn($query) => $query->where(function ($sub) use ($q, $len) {
                $sub->when($len === 4, fn($s) => $s->where('icao_code', 'ilike', $q))
                    ->orWhere('name', 'ilike', "%{$q}%")
                    ->orWhere('municipality', 'ilike', "%{$q}%");
            })->orderByRaw("
            CASE
                WHEN icao_code = ? THEN 0
                WHEN iata_code = ? THEN 1
                ELSE 2
            END
        ", [$q, $q]))
            ->limit(15)
            ->get(['id', 'name', 'municipality', 'iata_code', 'icao_code', 'region_id'])
            ->map(fn($airport) => [
                'value'        => $airport->id,
                'title'        => $airport->display_name,
                'country_code' => strtolower($airport->region->country->code),
            ])
            ->values();
    }
}
