import { NextRequest, NextResponse } from "next/server";
import { listAuditLogs } from "@/lib/log";

export async function GET(req: NextRequest) {
  try {
    const { searchParams } = req.nextUrl;
    const format = searchParams.get("format") || "json";

    // CSV export mode
    if (format === "csv") {
      const action = searchParams.get("action") || undefined;
      const resource = searchParams.get("resource") || undefined;
      const startDate = searchParams.get("startDate")
        ? new Date(searchParams.get("startDate")!)
        : undefined;
      const endDate = searchParams.get("endDate")
        ? new Date(searchParams.get("endDate")!)
        : undefined;

      // Fetch all matching rows (up to 10,000) for CSV export
      const result = await listAuditLogs({
        page: 1,
        pageSize: 10000,
        action: action || undefined,
        resource: resource || undefined,
        startDate,
        endDate,
      });

      const logs = result.logs as unknown as Array<{
        id: number; user_id: number; username: string; action: string;
        resource: string; resource_id: string | null; result: string;
        ip_address: string | null; created_at: Date;
      }>;

      const header = ["ID", "时间", "用户", "用户ID", "操作", "资源", "资源ID", "结果", "IP地址"];
      const rows = logs.map((log) => [
        log.id,
        new Date(log.created_at).toISOString(),
        log.username,
        log.user_id,
        log.action,
        log.resource,
        log.resource_id || "",
        log.result,
        log.ip_address || "",
      ]);

      const csvContent = [header, ...rows]
        .map((row) => row.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(","))
        .join("\n");

      const filename = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;

      return new NextResponse(csvContent, {
        headers: {
          "Content-Type": "text/csv; charset=utf-8",
          "Content-Disposition": `attachment; filename="${filename}"`,
        },
      });
    }

    // Normal JSON pagination mode
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const pageSize = Math.max(1, parseInt(searchParams.get("pageSize") || "20", 10));
    const userId = searchParams.get("userId")
      ? parseInt(searchParams.get("userId")!, 10)
      : undefined;
    const action = searchParams.get("action") || undefined;
    const resource = searchParams.get("resource") || undefined;
    const startDate = searchParams.get("startDate")
      ? new Date(searchParams.get("startDate")!)
      : undefined;
    const endDate = searchParams.get("endDate")
      ? new Date(searchParams.get("endDate")!)
      : undefined;

    const result = await listAuditLogs({
      page,
      pageSize,
      userId,
      action: action || undefined,
      resource: resource || undefined,
      startDate,
      endDate,
    });

    return NextResponse.json(result);
  } catch (e) {
    console.error("List audit logs error:", e);
    return NextResponse.json({ error: "服务器错误" }, { status: 500 });
  }
}
