<?php

namespace App\Models\Concerns;

use App\Models\AuditLog;

trait WritesAuditLog
{
    protected static function bootWritesAuditLog(): void
    {
        foreach (['created', 'updated', 'deleted'] as $event) {
            static::$event(function ($model) use ($event): void {
                AuditLog::create([
                    'business_id' => $model->business_id,
                    'user_id' => auth()->id(),
                    'event' => $event,
                    'auditable_type' => $model->getMorphClass(),
                    'auditable_id' => $model->getKey(),
                    'old_values' => $event === 'updated' ? array_intersect_key($model->getOriginal(), $model->getChanges()) : null,
                    'new_values' => $event === 'deleted' ? null : $model->getChanges(),
                    'ip_address' => request()?->ip(),
                    'user_agent' => request()?->userAgent(),
                    'created_at' => now(),
                ]);
            });
        }
    }
}
