<?php

namespace App\Traits;

use App\Models\AuditLog;

trait Auditable
{
    /**
     * Boot the auditable trait.
     */
    public static function bootAuditable(): void
    {
        static::created(function ($model) {
            AuditLog::log(
                'Create',
                $model->getTable(),
                $model->getKey(),
                null,
                $model->getAttributes()
            );
        });

        static::updated(function ($model) {
            // Only log if something actually changed
            $changes = $model->getChanges();
            if (!empty($changes)) {
                AuditLog::log(
                    'Update',
                    $model->getTable(),
                    $model->getKey(),
                    $model->getOriginal(),
                    $changes
                );
            }
        });

        static::deleted(function ($model) {
            AuditLog::log(
                'Delete',
                $model->getTable(),
                $model->getKey(),
                $model->getAttributes(),
                null
            );
        });
    }
}
