<?php

declare(strict_types=1);

namespace App\Models\Concerns;

use App\Services\DberpAuditService;
use App\Support\DberpAuditTrailGuard;
use Illuminate\Support\Facades\Auth;

trait HasDberpAuditTrail
{
    /**
     * @var array<string, mixed>
     */
    protected array $dberpAuditOriginalValues = [];

    public static function bootHasDberpAuditTrail(): void
    {
        static::created(function ($model): void {
            if (! DberpAuditTrailGuard::isEnabled() || ! Auth::check() || ! method_exists($model, 'getDberpAuditActionPrefix')) {
                return;
            }

            $audit = app(DberpAuditService::class);
            $audit->log(
                $model->getDberpAuditActionPrefix().'.created',
                $model,
                null,
                $audit->snapshot($model, $model->getDberpAuditFields()),
            );
        });

        static::updating(function ($model): void {
            if (! DberpAuditTrailGuard::isEnabled() || ! Auth::check() || ! method_exists($model, 'getDberpAuditActionPrefix')) {
                return;
            }

            $model->dberpAuditOriginalValues = app(DberpAuditService::class)->snapshotFromArray(
                $model->getOriginal(),
                $model->getDberpAuditFields(),
            );
        });

        static::updated(function ($model): void {
            if (! DberpAuditTrailGuard::isEnabled() || ! Auth::check() || ! method_exists($model, 'getDberpAuditActionPrefix')) {
                return;
            }

            $auditedFields = $model->getDberpAuditFields();
            $changedKeys = array_keys($model->getChanges());

            if ($changedKeys === [] || array_intersect($auditedFields, $changedKeys) === []) {
                $model->dberpAuditOriginalValues = [];

                return;
            }

            $audit = app(DberpAuditService::class);
            $audit->log(
                $model->getDberpAuditActionPrefix().'.updated',
                $model,
                $model->dberpAuditOriginalValues,
                $audit->snapshot($model, $model->getDberpAuditFields()),
            );

            $model->dberpAuditOriginalValues = [];
        });

        static::deleted(function ($model): void {
            if (! DberpAuditTrailGuard::isEnabled() || ! Auth::check() || ! method_exists($model, 'getDberpAuditActionPrefix')) {
                return;
            }

            $audit = app(DberpAuditService::class);
            $audit->log(
                $model->getDberpAuditActionPrefix().'.deleted',
                $model,
                $audit->snapshot($model, $model->getDberpAuditFields()),
                null,
            );
        });
    }
}
