<?php

namespace Modules\Catalog\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Modules\Catalog\Database\Factories\DepartureTimeSlotFactory;
use Modules\Routing\Models\EvRoute;
use Spatie\Activitylog\Models\Concerns\LogsActivity;
use Spatie\Activitylog\Support\LogOptions;

/**
 * A shared catalog of departure times, attached to routes via a pivot in the
 * Routing module — not owned by any single route.
 */
class DepartureTimeSlot extends Model
{
    /** @use HasFactory<DepartureTimeSlotFactory> */
    use HasFactory, LogsActivity;

    /**
     * Full CRUD audit trail — catalog 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('catalog');
    }

    /**
     * @var list<string>
     */
    protected $fillable = [
        'label',
        'time',
        'is_active',
    ];

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

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