<?php

namespace App\Models;

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

class SubscriptionAuditLog extends Model
{
    protected $fillable = [
        'subscription_id',
        'admin_id',
        'action',
        'old_value',
        'new_value',
        'metadata',
        'notes',
        'ip_address',
    ];

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

    /**
     * Action types.
     */
    const ACTION_STATUS_CHANGED = 'status_changed';
    const ACTION_PAYMENT_CONFIRMED = 'payment_confirmed';
    const ACTION_PLAN_CHANGED = 'plan_changed';
    const ACTION_EXTENDED = 'extended';
    const ACTION_CANCELLED = 'cancelled';
    const ACTION_SUSPENDED = 'suspended';
    const ACTION_REACTIVATED = 'reactivated';
    const ACTION_NOTES_ADDED = 'notes_added';
    const ACTION_MANUAL_ACTIVATION = 'manual_activation';

    /**
     * Get the subscription.
     */
    public function subscription(): BelongsTo
    {
        return $this->belongsTo(Subscription::class);
    }

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

    /**
     * Create an audit log entry.
     */
    public static function log(
        int $subscriptionId, 
        string $action, 
        ?string $oldValue = null, 
        ?string $newValue = null, 
        ?array $metadata = null, 
        ?string $notes = null
    ): self {
        return static::create([
            'subscription_id' => $subscriptionId,
            'admin_id' => auth()->id(),
            'action' => $action,
            'old_value' => $oldValue,
            'new_value' => $newValue,
            'metadata' => $metadata,
            'notes' => $notes,
            'ip_address' => request()->ip(),
        ]);
    }

    /**
     * Get human-readable action label.
     */
    public function getActionLabelAttribute(): string
    {
        $labels = [
            self::ACTION_STATUS_CHANGED => 'Estado cambiado',
            self::ACTION_PAYMENT_CONFIRMED => 'Pago confirmado',
            self::ACTION_PLAN_CHANGED => 'Plan cambiado',
            self::ACTION_EXTENDED => 'Suscripción extendida',
            self::ACTION_CANCELLED => 'Suscripción cancelada',
            self::ACTION_SUSPENDED => 'Suscripción suspendida',
            self::ACTION_REACTIVATED => 'Suscripción reactivada',
            self::ACTION_NOTES_ADDED => 'Notas agregadas',
            self::ACTION_MANUAL_ACTIVATION => 'Activación manual',
        ];

        return $labels[$this->action] ?? $this->action;
    }
}
