<?php

namespace App\Observers;

use App\Enums\DeclarationStatus;
use App\Models\Declaration;
use Illuminate\Validation\ValidationException;

class DeclarationObserver
{
    /**
     * Handle the Declaration "updating" event.
     *
     * Validates status transitions and auto-archives when status becomes "ferme".
     */
    public function updating(Declaration $declaration): void
    {
        if (! $declaration->isDirty('status')) {
            return;
        }

        $oldStatus = $declaration->getOriginal('status');
        $newStatus = $declaration->status;

        // Handle both string and enum values
        $oldValue = $oldStatus instanceof DeclarationStatus ? $oldStatus->value : (string) $oldStatus;
        $newValue = $newStatus instanceof DeclarationStatus ? $newStatus->value : (string) $newStatus;

        $allowed = DeclarationStatus::allowedTransitions()[$oldValue] ?? [];

        if (! in_array($newValue, $allowed)) {
            throw ValidationException::withMessages([
                'status' => "Invalid status transition from '{$oldValue}' to '{$newValue}'.",
            ]);
        }

        // Auto-archive when status becomes "ferme"
        if ($newValue === DeclarationStatus::Ferme) {
            $declaration->archived_at = now();
        }
    }
}
