<?php

namespace App\Models;

use App\Observers\AirlineObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

#[ObservedBy(AirlineObserver::class)]
class Airline extends Model
{
    protected $table = 'airlines';

    protected $fillable = [
        'iata_code',
        'icao_code',
        'name',
        'internal_name',
        'country_id',
        'alliance_id',
        'active',
        'logo',
        'merged_into_id',
    ];

    protected $casts = [
        'active' => 'boolean',
    ];

    public $timestamps = false;
    protected $appends = [
        'display_name',
        'logo_url',
    ];

    protected function displayName() : Attribute{
        return Attribute::make(
            get: function () {
                $codes = array_filter([$this->iata_code, $this->icao_code]);
                $codeString = count($codes) ? ' (' . implode('/', $codes) . ')' : '';
                return "{$this->name}{$codeString}";
            }
        );
    }

    protected function logoUrl() : Attribute{
        return Attribute::make(
            get: function () {
                $user = auth()->user();
                $apiUrl = config('app.logo_api_url');
                if ($user && !$user->getSetting('ai_tail_logos')) {
                    return $apiUrl .'/airline/blank/logo/tail';
                }

                return $apiUrl . "/airline/$this->internal_name/logo/tail";
            }
        );
    }

    public function alliance(): BelongsTo
    {
        return $this->belongsTo(Alliance::class);
    }

    public function country(): BelongsTo
    {
        return $this->belongsTo(Country::class);
    }

    public function mergedInto(): BelongsTo
    {
        return $this->belongsTo(Airline::class, 'merged_into_id');
    }

    public function mergedFrom(): HasMany
    {
        return $this->hasMany(Airline::class, 'merged_into_id');
    }

    public function canonical(): self
    {
        return $this->mergedInto ?? $this;
    }
}
