<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Alliance extends Model
{

    protected $table = 'alliances';

    protected $fillable = [
        'internal_name',
        'name',
    ];

    protected $casts = [
        'internal_name' => 'string',
    ];

    const ALLIANCE_CHALLENGES = [
        'star_alliance' => 'airlines_alliances.all_star_alliance',
        'oneworld' => 'airlines_alliances.all_oneworld',
        'vanilla_alliance' => 'airlines_alliances.all_vanilla_alliance',
        'skyteam' => 'airlines_alliances.all_skyteam',
    ];

    public function airlines(): HasMany
    {
        return $this->hasMany(Airline::class);
    }

    public static function recalculateChallengeThresholds() : void {
        $alliances = Alliance::all();
        foreach ($alliances as $alliance) {
            $airlineCount = $alliance->airlines()->count();
            $challenge = self::ALLIANCE_CHALLENGES[$alliance->internal_name];
            Achievement::where('internal_name', $challenge)->update(['threshold' => $airlineCount]);
        }

    }
}
