<?php

namespace App\Models;

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

class AdminAuditLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'admin_id',
        'action',
        'resource_type',
        'resource_id',
        'old_values',
        'new_values',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'old_values' => 'array',
        'new_values' => 'array',
    ];

    /**
     * Get the admin who performed the action.
     */
    public function admin()
    {
        return $this->belongsTo(Admin::class);
    }

    /**
     * Log an admin action.
     */
    public static function logAction(
        Admin $admin,
        string $action,
        ?string $resourceType = null,
        ?int $resourceId = null,
        ?array $oldValues = null,
        ?array $newValues = null
    ): self {
        return self::create([
            'admin_id' => $admin->id,
            'action' => $action,
            'resource_type' => $resourceType,
            'resource_id' => $resourceId,
            'old_values' => $oldValues,
            'new_values' => $newValues,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);
    }

    /**
     * Common action types.
     */
    const ACTION_LOGIN = 'login';
    const ACTION_LOGOUT = 'logout';
    const ACTION_CREATE = 'create';
    const ACTION_UPDATE = 'update';
    const ACTION_DELETE = 'delete';
    const ACTION_TOGGLE_STATUS = 'toggle_status';
    const ACTION_FORCE_LOGOUT = 'force_logout';
    const ACTION_RESET_PASSWORD = 'reset_password';
    const ACTION_VIEW_SENSITIVE = 'view_sensitive';
    const ACTION_EXPORT = 'export';
    const ACTION_PERMISSION_DENIED = 'permission_denied';

    /**
     * Get action description for display.
     */
    public function getActionDescription(): string
    {
        return match($this->action) {
            self::ACTION_LOGIN => 'Logged in',
            self::ACTION_LOGOUT => 'Logged out',
            self::ACTION_CREATE => 'Created ' . $this->resource_type,
            self::ACTION_UPDATE => 'Updated ' . $this->resource_type,
            self::ACTION_DELETE => 'Deleted ' . $this->resource_type,
            self::ACTION_TOGGLE_STATUS => 'Toggled status of ' . $this->resource_type,
            self::ACTION_FORCE_LOGOUT => 'Forced logout of ' . $this->resource_type,
            self::ACTION_RESET_PASSWORD => 'Reset password for ' . $this->resource_type,
            self::ACTION_VIEW_SENSITIVE => 'Viewed sensitive data in ' . $this->resource_type,
            self::ACTION_EXPORT => 'Exported ' . $this->resource_type,
            self::ACTION_PERMISSION_DENIED => 'Permission denied for ' . $this->action,
            default => ucfirst(str_replace('_', ' ', $this->action)),
        };
    }
}
