import { NextResponse } from "next/server"

import { getAuditRetentionConfig, purgeExpiredAuditLogs } from "@/modules/audit/retention"
import { trackEvent } from "@/shared/lib/track-event"

/**
 * 审计日志定时清理 Cron 端点
 *
 * 部署方式（Vercel Cron Jobs）：
 * 在 `vercel.json` 中配置：
 * ```json
 * {
 *   "crons": [
 *     { "path": "/api/cron/audit-cleanup", "schedule": "0 3 * * *" }
 *   ]
 * }
 * ```
 *
 * 鉴权：通过 `CRON_SECRET` 环境变量校验 Authorization Bearer token。
 * 本地测试：`curl -H "Authorization: Bearer $CRON_SECRET" http://localhost:3000/api/cron/audit-cleanup`
 */
export const dynamic = "force-dynamic"

export async function GET(request: Request): Promise<NextResponse> {
  try {
    // 鉴权：校验 CRON_SECRET
    const authHeader = request.headers.get("authorization")
    const secret = process.env.CRON_SECRET
    if (!secret) {
      console.error("[audit-cleanup] CRON_SECRET is not configured")
      return NextResponse.json({ error: "Cron secret not configured" }, { status: 500 })
    }
    if (authHeader !== `Bearer ${secret}`) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    // 读取保留策略配置
    const config = await getAuditRetentionConfig()

    // 未启用自动清理则跳过
    if (!config.autoCleanupEnabled) {
      return NextResponse.json({
        ok: true,
        message: "Auto cleanup is disabled, skipping",
        config,
      })
    }

    // 执行清理（audit-P2-5: login_logs 使用独立保留期，默认 365 天）
    const result = await purgeExpiredAuditLogs(
      config.retentionDays,
      config.loginLogRetentionDays,
    )

    // 埋点记录
    void trackEvent({
      event: "audit.retention",
      targetType: "audit_retention",
      properties: {
        action: "cron_purge",
        retentionDays: config.retentionDays,
        ...result,
      },
    })

    return NextResponse.json({
      ok: true,
      config,
      result,
    })
  } catch (error) {
    console.error("[audit-cleanup] failed:", error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Unknown error" },
      { status: 500 },
    )
  }
}
