<?php

namespace App\Services\Achievements\Checkers;

use App\Models\Airline;
use App\Models\Alliance;
use App\Models\User;
use App\Models\UserFlight;
use Illuminate\Support\Collection;

class AirlinesAndAlliancesChecker extends BaseChecker
{
    const array US_3 = ['american-airlines', 'delta', 'united-airlines'];
    const array ME_3 = ['emirates', 'etihad-airways', 'qatar-airways'];
    const array CN_3 = ['china-southern-airlines', 'china-eastern', 'air-china'];

    public function check(): void
    {
        $flights = $this->flights();

        $alliances = Alliance::withCount('airlines')->pluck('id', 'internal_name');

        $flownAllianceAirlines = $flights
            ->map(fn(UserFlight $f) => $f->airline?->canonical())
            ->filter(fn(?Airline $a) => $a?->alliance !== null)
            ->groupBy(fn(Airline $a) => $a->alliance->internal_name)
            ->map(fn($group) => $group->pluck('internal_name')->unique()->count());

        $check = fn(string $alliance): int => $flownAllianceAirlines->get($alliance, 0);

        $this->awardProgress($check('skyteam'),          'airlines_alliances.all_skyteam');
        $this->awardProgress($check('oneworld'),         'airlines_alliances.all_oneworld');
        $this->awardProgress($check('star_alliance'),    'airlines_alliances.all_star_alliance');
        $this->awardProgress($check('vanilla_alliance'), 'airlines_alliances.all_vanilla_alliance');

        $flownAirlines = $flights
            ->pluck('airline.internal_name')
            ->filter()
            ->unique();

        $checkGroup = fn(array $group): int => $flownAirlines->intersect($group)->count();

        $this->awardProgress($checkGroup(self::ME_3), 'airlines_alliances.me3');
        $this->awardProgress($checkGroup(self::US_3), 'airlines_alliances.us3');
        $this->awardProgress($checkGroup(self::CN_3), 'airlines_alliances.cn3');
    }
}
