<?php

namespace App\Models\Concerns;

use App\Services\Audit\AuditLogger;

trait Auditable
{
    public static function bootAuditable(): void
    {
        static::created(function ($model) {
            app(AuditLogger::class)->log('created', $model, null, $model->getAttributes());
        });

        static::updated(function ($model) {
            if ($model->wasChanged()) {
                app(AuditLogger::class)->log(
                    'updated',
                    $model,
                    collect($model->getOriginal())->only(array_keys($model->getChanges()))->all(),
                    $model->getChanges(),
                );
            }
        });

        static::deleted(function ($model) {
            app(AuditLogger::class)->log('deleted', $model, $model->getOriginal(), null);
        });
    }
}
