<?php

namespace Modules\Routing\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
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;
use Spatie\Activitylog\Models\Concerns\LogsActivity;
use Spatie\Activitylog\Support\LogOptions;

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

    /**
     * Full CRUD audit trail — route admin writes are staff-only and
     * infrequent, so logging every attribute change is affordable
     * (domain.md §6; T6.2).
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontLogEmptyChanges()
            ->useLogName('routing');
    }

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

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            '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');
    }

    public function name(): Attribute
    {
        return Attribute::make(
            get: fn (): string => $this->fromDestination->name.' → '.$this->toDestination->name,
        );
    }

    /**
     * True when this route is the exact reverse direction of $other (from
     * and to swapped) — used to validate a booking's `return_ev_route_id`
     * is genuinely the return leg of its outbound route, not an unrelated
     * pair (domain.md §2b).
     */
    public function isReverseOf(EvRoute $other): bool
    {
        return $this->from_destination_id === $other->to_destination_id
            && $this->to_destination_id === $other->from_destination_id;
    }
}
