<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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,
            );
        });
    }
}
