<?php

declare(strict_types=1);

namespace Kylin\Scaffold\Traits;

/**
 * 安装审计日志 Trait
 *
 * 依据等保 2.0 (GB/T 22239) 8.1.4.6：
 * 安装操作需记录审计日志。
 *
 * 使用方式：
 *   class ScaffoldInstallCommand
 *   {
 *       use ScaffoldAudit;
 *
 *       public function handle(): int
 *       {
 *           $this->auditInstall('install_started', [
 *               'modules' => $selected,
 *               'options' => $this->options(),
 *           ]);
 *           // ... 安装逻辑 ...
 *           $this->auditInstall('install_completed', [
 *               'modules' => $selected,
 *               'duration' => $duration,
 *           ]);
 *       }
 *   }
 */
trait ScaffoldAudit
{
    /**
     * 写入安装审计日志
     *
     * @param string $event 事件名（install_started, install_completed, module_installed, install_failed）
     * @param array $data 审计数据
     */
    protected function auditInstall(string $event, array $data = []): void
    {
        if (! class_exists(\Kylin\AuditLog\Models\AuditLog::class)) {
            return;
        }

        try {
            \Kylin\AuditLog\Models\AuditLog::create([
                'event' => $event,
                'model_type' => 'scaffold',
                'model_id' => 0,
                'new_values' => $data,
                'user_id' => auth()->id() ?? 0,
                'ip' => request()->ip() ?? 'console',
                'url' => 'console',
                'tag' => 'scaffold',
            ]);
        } catch (\Throwable $e) {
            logger()->warning('安装审计日志写入失败', [
                'event' => $event,
                'error' => $e->getMessage(),
            ]);
        }
    }
}