<?php

namespace App\Models;

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

class CoachPlanAuditLog extends Model
{
    protected $fillable = [
        'coach_plan_id',
        'user_id',
        'action',
        'field_changed',
        'old_value',
        'new_value',
        'changes_summary',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'changes_summary' => 'array',
    ];

    /**
     * Get the plan that was audited.
     */
    public function coachPlan(): BelongsTo
    {
        return $this->belongsTo(CoachPlan::class);
    }

    /**
     * Get the user who made the change.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get action label in Spanish.
     */
    public function getActionLabelAttribute(): string
    {
        return match($this->action) {
            'created' => 'Creado',
            'updated' => 'Actualizado',
            'published' => 'Publicado',
            'unpublished' => 'Despublicado',
            'deleted' => 'Eliminado',
            'autosaved' => 'Guardado automático',
            'image_uploaded' => 'Imagen subida',
            'image_deleted' => 'Imagen eliminada',
            'result_added' => 'Resultado agregado',
            'result_removed' => 'Resultado eliminado',
            default => ucfirst($this->action),
        };
    }

    /**
     * Get a summary of changes made.
     */
    public function getChangesSummaryTextAttribute(): string
    {
        if (!$this->changes_summary) {
            return $this->field_changed 
                ? "Campo '{$this->field_changed}' modificado"
                : 'Sin cambios registrados';
        }

        $count = count($this->changes_summary);
        return $count === 1 
            ? "1 campo modificado"
            : "{$count} campos modificados";
    }

    /**
     * Create a log entry for a plan action.
     */
    public static function logAction(
        CoachPlan $plan,
        string $action,
        ?array $changes = null,
        ?string $fieldChanged = null,
        mixed $oldValue = null,
        mixed $newValue = null
    ): self {
        return self::create([
            'coach_plan_id' => $plan->id,
            'user_id' => auth()->id(),
            'action' => $action,
            'field_changed' => $fieldChanged,
            'old_value' => is_array($oldValue) ? json_encode($oldValue) : $oldValue,
            'new_value' => is_array($newValue) ? json_encode($newValue) : $newValue,
            'changes_summary' => $changes,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);
    }
}
