<?php

namespace Kylin\AuditLog\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\AuditLog\Models\AuditLog;
use Kylin\AuditLog\Services\AuditLogService;
use Kylin\AuditLog\Traits\AuditLogViewAudit;

/**
 * 审计日志控制器
 *
 * 提供审计日志的查询分页 API。
 *
 * 合规要求：
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.1，日志查看需进行访问控制
 *  - 依据等保 2.0 (GB/T 22239) 8.1.4.6，查看日志操作需被审计
 */
class AuditLogController extends BaseController
{
    use AuditLogViewAudit;

    public function __construct(private readonly AuditLogService $service) {}

    public function index(Request $request): JsonResponse
    {
        $this->authorize('viewAny', AuditLog::class);

        // 审计：记录谁在什么时间查看了什么日志
        $this->auditViewLog('audit_log_viewed', $request->only(['model_type', 'event', 'user_id', 'date_from', 'date_to']));

        $logs = $this->service->list($request->only(['model_type', 'event', 'user_id', 'date_from', 'date_to']), $request->input('per_page', 15));
        return ApiResponse::paginate($logs);
    }

    public function clean(Request $request): JsonResponse
    {
        $this->authorize('delete', AuditLog::class);

        // 审计：记录清理操作
        $this->auditViewLog('audit_log_cleaned', ['days' => $request->input('days')]);

        $days = $request->input('days', config('kylin-audit-log.keep_days', 90));
        $count = $this->service->clean($days);
        return ApiResponse::success(['deleted' => $count], "已清理 {$count} 条日志");
    }
}