<?php

// app/Models/FiscalAssignmentHistory.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class FiscalAssignmentHistory extends Model
{
    use HasFactory;

    protected $table = 'fiscal_assignment_history';

    public $timestamps = false; // Usamos apenas created_at

    protected $fillable = [
        'assignment_id',
        'action',
        'old_data',
        'new_data',
        'performed_by',
        'created_at',
    ];

    protected $casts = [
        'old_data' => 'array',
        'new_data' => 'array',
        'created_at' => 'datetime',
    ];

    /**
     * Relacionamento com a atribuição
     */
    public function assignment(): BelongsTo
    {
        return $this->belongsTo(FiscalMarketAssignment::class, 'assignment_id');
    }

    /**
     * Relacionamento com o usuário que realizou a ação
     */
    public function performedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'performed_by');
    }

    /**
     * Scope para filtrar por ação
     */
    public function scopeOfAction($query, $action)
    {
        return $query->where('action', $action);
    }

    /**
     * Scope para filtrar por período
     */
    public function scopeInPeriod($query, $startDate, $endDate)
    {
        return $query->whereBetween('created_at', [$startDate, $endDate]);
    }

    /**
     * Obter label da ação
     */
    public function getActionLabelAttribute(): string
    {
        return match ($this->action) {
            'assigned' => 'Atribuído',
            'updated' => 'Atualizado',
            'removed' => 'Removido',
            'expired' => 'Expirado',
            default => $this->action
        };
    }

    /**
     * Obter cor da ação para UI
     */
    public function getActionColorAttribute(): string
    {
        return match ($this->action) {
            'assigned' => 'success',
            'updated' => 'info',
            'removed' => 'danger',
            'expired' => 'warning',
            default => 'secondary'
        };
    }

    /**
     * Obter ícone da ação
     */
    public function getActionIconAttribute(): string
    {
        return match ($this->action) {
            'assigned' => 'fa-check-circle',
            'updated' => 'fa-edit',
            'removed' => 'fa-times-circle',
            'expired' => 'fa-clock',
            default => 'fa-history'
        };
    }

    /**
     * Registrar uma ação no histórico
     */
    public static function log($assignmentId, $action, $oldData = null, $newData = null): self
    {
        return self::create([
            'assignment_id' => $assignmentId,
            'action' => $action,
            'old_data' => $oldData,
            'new_data' => $newData,
            'performed_by' => auth()->id(),
            'created_at' => now(),
        ]);
    }

    /**
     * Obter resumo da alteração
     */
    public function getChangesSummaryAttribute(): ?string
    {
        if (! $this->old_data || ! $this->new_data || $this->action !== 'updated') {
            return null;
        }

        $changes = [];
        $old = $this->old_data;
        $new = $this->new_data;

        // Verificar mudanças em campos importantes
        if (($old['assigned_zones'] ?? null) != ($new['assigned_zones'] ?? null)) {
            $changes[] = 'zonas alteradas';
        }

        if (($old['primary_fiscal'] ?? null) != ($new['primary_fiscal'] ?? null)) {
            $changes[] = 'status de fiscal principal '.($new['primary_fiscal'] ? 'ativado' : 'desativado');
        }

        if (($old['start_date'] ?? null) != ($new['start_date'] ?? null)) {
            $changes[] = 'data de início alterada';
        }

        if (($old['end_date'] ?? null) != ($new['end_date'] ?? null)) {
            $changes[] = 'data de término '.($new['end_date'] ? 'definida' : 'removida');
        }

        return implode(', ', $changes) ?: 'detalhes atualizados';
    }
}
