<?php

declare(strict_types=1);

namespace Kylin\AuditLog\Traits;

/**
 * 日志查看审计 Trait
 *
 * 依据等保 2.0 (GB/T 22239) 8.1.4.6：
 * 查看审计日志的操作本身也需要被审计记录。
 *
 * 使用方式：
 *   class AuditLogController
 *   {
 *       use AuditLogViewAudit;
 *
 *       public function index(Request $request): JsonResponse
 *       {
 *           $this->auditViewLog('audit_log_viewed', $request->all());
 *           // ...
 *       }
 *   }
 */
trait AuditLogViewAudit
{
    /**
     * 审计日志查看操作
     *
     * @param string $event 事件名
     * @param array $filters 查询过滤条件
     */
    protected function auditViewLog(string $event, array $filters = []): void
    {
        if (! class_exists(\Kylin\AuditLog\Models\AuditLog::class)) {
            return;
        }

        try {
            \Kylin\AuditLog\Models\AuditLog::create([
                'event' => $event,
                'model_type' => 'audit_log',
                'model_id' => 0,
                'new_values' => [
                    'filters' => $filters,
                    'viewed_at' => now()->toDateTimeString(),
                ],
                'user_id' => auth()->id(),
                'ip' => request()->ip(),
                'url' => request()->fullUrl(),
                'tag' => 'audit-view',
            ]);
        } catch (\Throwable $e) {
            logger()->warning('审计日志查看审计写入失败', [
                'event' => $event,
                'error' => $e->getMessage(),
            ]);
        }
    }
}