<?php

namespace App\Models;

use App\Enums\TimelineStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Timeline extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'case_name',
        'case_reference',
        'status',
    ];

    protected function casts(): array
    {
        return [
            'status' => TimelineStatus::class,
        ];
    }

    /**
     * Get the user that owns the timeline.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the updates for the timeline, ordered chronologically (oldest first).
     */
    public function updates(): HasMany
    {
        return $this->hasMany(TimelineUpdate::class)->orderBy('created_at', 'asc');
    }

    /**
     * Archive the timeline.
     */
    public function archive(): void
    {
        $this->update(['status' => TimelineStatus::Archived]);
    }

    /**
     * Unarchive the timeline.
     */
    public function unarchive(): void
    {
        $this->update(['status' => TimelineStatus::Active]);
    }

    /**
     * Check if the timeline is archived.
     */
    public function isArchived(): bool
    {
        return $this->status === TimelineStatus::Archived;
    }

    /**
     * Check if the timeline is active.
     */
    public function isActive(): bool
    {
        return $this->status === TimelineStatus::Active;
    }

    /**
     * Scope a query to only include active timelines.
     */
    public function scopeActive($query)
    {
        return $query->where('status', TimelineStatus::Active);
    }

    /**
     * Scope a query to only include archived timelines.
     */
    public function scopeArchived($query)
    {
        return $query->where('status', TimelineStatus::Archived);
    }
}
