<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Airport extends Model
{
    protected $fillable = [
        'type',
        'name',
        'latitude_deg',
        'longitude_deg',
        'elevation_ft',
        'timezone',
        'region_id',
        'municipality',
        'icao_code',
        'iata_code',
        'local_code',
    ];

    protected $casts = [
        'latitude_deg'  => 'float',
        'longitude_deg' => 'float',
        'elevation_ft'  => 'integer',
    ];

    protected $appends = [
        'display_code',
        'display_name',
    ];

    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->municipality} / {$this->name}{$codeString}";
            }
        );
    }
    protected function displayCode(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->iata_code ?? $this->icao_code ?? $this->local_code ?? '---'
        );
    }

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