<?php

declare(strict_types=1);

namespace Kylin\RiskControl\Traits;

/**
 * 风控操作审计日志 Trait
 *
 * 依据等保 2.0 (GB/T 22239) 8.1.4.6：
 * 风控操作（审批、评分、分类）需记录审计日志。
 *
 * 使用方式：
 *   class RiskControlService
 *   {
 *       use RiskControlAudit;
 *
 *       public function approve(Application $application): void
 *       {
 *           // ... 业务逻辑 ...
 *
 *           $this->auditRisk('risk_approved', 'application', $application->id, [
 *               'application_id' => $application->id,
 *               'amount' => $application->amount,
 *           ]);
 *       }
 *   }
 */
trait RiskControlAudit
{
    /**
     * 写入风控审计日志
     */
    protected function auditRisk(string $event, string $modelType, int|string $modelId, array $data = []): void
    {
        if (! class_exists(\Kylin\AuditLog\Models\AuditLog::class)) {
            return;
        }

        // 脱敏金额信息
        $masked = $data;
        unset($masked['amount'], $masked['id_card'], $masked['phone']);

        try {
            \Kylin\AuditLog\Models\AuditLog::create([
                'event' => $event,
                'model_type' => $modelType,
                'model_id' => $modelId,
                'new_values' => $masked,
                'user_id' => auth()->id(),
                'ip' => request()->ip(),
                'url' => request()->fullUrl(),
                'tag' => 'risk-control',
            ]);
        } catch (\Throwable $e) {
            logger()->warning('风控审计日志写入失败', [
                'event' => $event,
                'error' => $e->getMessage(),
            ]);
        }
    }
}