<?php

namespace Modules\Routing\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use InvalidArgumentException;
use Modules\Catalog\Models\Destination;
use Modules\Routing\Database\Factories\PopularRouteFactory;
use Spatie\Activitylog\Models\Concerns\LogsActivity;
use Spatie\Activitylog\Support\LogOptions;

class PopularRoute extends Model
{
    /** @use HasFactory<PopularRouteFactory> */
    use HasFactory, LogsActivity;

    /**
     * Full CRUD audit trail — staff-curated content, infrequent writes
     * (domain.md §6; T6.2), same as EvRoute/Destination.
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontLogEmptyChanges()
            ->useLogName('routing');
    }

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

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

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

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

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