<?php

namespace App\Traits;

use App\Models\AdminActivityLog;
use App\Models\BulkOperation;
use Illuminate\Database\Eloquent\Model;

/**
 * Trait AdminAuditableTrait
 *
 * Add audit trail functionality to any model
 * Automatically logs create, update, delete operations
 */
trait AdminAuditableTrait
{
    /**
     * Boot the trait
     */
    public static function bootAdminAuditableTrait()
    {
        static::created(function (Model $model) {
            if (auth()->check() && auth()->user()->hasAnyRole(['admin', 'super_admin'])) {
                AdminActivityLog::createFromRequest(
                    auth()->id(),
                    'create',
                    class_basename($model),
                    $model->id,
                    $model->name ?? $model->title ?? "ID: {$model->id}",
                    description: "Created new " . strtolower(class_basename($model))
                );
            }
        });

        static::updated(function (Model $model) {
            if (auth()->check() && auth()->user()->hasAnyRole(['admin', 'super_admin'])) {
                $changes = $model->getChanges();
                if (!empty($changes)) {
                    AdminActivityLog::createFromRequest(
                        auth()->id(),
                        'update',
                        class_basename($model),
                        $model->id,
                        $model->name ?? $model->title ?? "ID: {$model->id}",
                        $model->getOriginal(),
                        $model->getAttributes(),
                        description: "Updated " . strtolower(class_basename($model))
                    );
                }
            }
        });

        static::deleted(function (Model $model) {
            if (auth()->check() && auth()->user()->hasAnyRole(['admin', 'super_admin'])) {
                AdminActivityLog::createFromRequest(
                    auth()->id(),
                    'delete',
                    class_basename($model),
                    $model->id,
                    $model->name ?? $model->title ?? "ID: {$model->id}",
                    $model->getAttributes(),
                    description: "Deleted " . strtolower(class_basename($model)),
                    isSensitive: true
                );
            }
        });
    }
}

