<?php

namespace Modules\Routing\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use InvalidArgumentException;
use Modules\Catalog\Models\DepartureTimeSlot;
use Modules\Catalog\Models\Destination;
use Modules\Catalog\Models\EvCompany;
use Modules\Routing\Database\Factories\EvRouteFactory;

class EvRoute extends Model
{
    /** @use HasFactory<EvRouteFactory> */
    use HasFactory;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'ev_company_id',
        'from_destination_id',
        'to_destination_id',
        'is_round_trip',
        'is_active',
    ];

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_round_trip' => 'boolean',
            'is_active' => 'boolean',
        ];
    }

    protected static function booted(): void
    {
        static::saving(function (self $route): void {
            if ($route->from_destination_id === $route->to_destination_id) {
                throw new InvalidArgumentException("A route's from and to destinations must be different.");
            }
        });
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(EvCompany::class, 'ev_company_id');
    }

    public function fromDestination(): BelongsTo
    {
        return $this->belongsTo(Destination::class, 'from_destination_id');
    }

    public function toDestination(): BelongsTo
    {
        return $this->belongsTo(Destination::class, 'to_destination_id');
    }

    public function timeSlots(): BelongsToMany
    {
        return $this->belongsToMany(DepartureTimeSlot::class, 'ev_route_time_slots')
            ->withPivot('is_active')
            ->withTimestamps();
    }

    public function pricing(): HasMany
    {
        return $this->hasMany(RoutePricing::class, 'ev_route_id');
    }
}
