<?php

namespace App\Traits;

use App\Models\Audit;
use Illuminate\Support\Facades\Auth;

trait Auditable
{
    public static function bootAuditable(): void
    {
        static::creating(function ($model) {
            $model->recordAudit('created', [], $model->getAttributes());
        });

        static::updating(function ($model) {
            $original = $model->getOriginal();
            $changes = $model->getChanges();
            // Avoid recording audit if no meaningful changes
            if (empty($changes)) {
                return;
            }

            $model->recordAudit('updated', array_intersect_key($original, $changes), $changes);
        });

        static::deleting(function ($model) {
            $model->recordAudit('deleted', $model->getAttributes(), []);
        });
    }

    protected function recordAudit(string $event, array $oldValues = [], array $newValues = []): void
    {
        try {
            Audit::create([
                'auditable_type' => static::class,
                'auditable_id' => $this->getKey(),
                'user_id' => Auth::id(),
                'event' => $event,
                'old_values' => $oldValues ?: null,
                'new_values' => $newValues ?: null,
                'ip_address' => request()->ip(),
                'user_agent' => request()->userAgent(),
            ]);
        } catch (\Throwable $e) {
            // If audit logging fails, do not block the request.
        }
    }
}
