import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  getAuditLogs,
  getAuditLogTypes,
  exportAuditLogsToCSV,
  type AuditLogFilters,
} from "@/lib/services/security-audit.service";
import { getDataSource } from "@/lib/data-source";
import { convexQuery } from "@/lib/convex-client";

export async function GET(request: NextRequest) {
  try {
    const session = await validateStaffSession(request);
    if (
      !session ||
      (session.role !== "ADMIN" && session.role !== "SUPER_ADMIN")
    ) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { searchParams } = new URL(request.url);
    const action = searchParams.get("action");

    // --- Convex path (non-export only; CSV export stays Prisma) ---
    if (getDataSource("auth") === "convex" && action !== "export") {
      try {
        // Get distinct types for filter dropdown
        if (action === "types") {
          const types = await convexQuery(
            (api.auth.queries as any).getAuditLogTypes,
            {},
          );
          return NextResponse.json({ types: types ?? [] });
        }

        // Get paginated audit logs
        const filters = buildFilters(searchParams);
        const result = await convexQuery(
          (api.auth.queries as any).getAuditLogsStaff,
          {
            userId: filters.userId,
            type: filters.type,
            action: filters.action,
            success: filters.success,
            ip: filters.ip,
            startDate: filters.startDate
              ? filters.startDate.getTime()
              : undefined,
            endDate: filters.endDate ? filters.endDate.getTime() : undefined,
            page: filters.page,
            limit: filters.limit,
          },
        );

        return NextResponse.json(result);
      } catch (convexErr) {
        console.error(
          "Convex audit logs failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    // Get distinct types for filter dropdown
    if (action === "types") {
      const types = await getAuditLogTypes();
      return NextResponse.json({ types });
    }

    // Export to CSV
    if (action === "export") {
      const filters = buildFilters(searchParams);
      const csv = await exportAuditLogsToCSV(filters);

      return new NextResponse(csv, {
        headers: {
          "Content-Type": "text/csv",
          "Content-Disposition": `attachment; filename="audit-logs-${new Date().toISOString().split("T")[0]}.csv"`,
        },
      });
    }

    // Get paginated audit logs
    const filters = buildFilters(searchParams);
    const result = await getAuditLogs(filters);

    return NextResponse.json(result);
  } catch (error) {
    console.error("Failed to fetch audit logs:", error);
    return NextResponse.json(
      { error: "Failed to fetch audit logs" },
      { status: 500 },
    );
  }
}

function buildFilters(searchParams: URLSearchParams): AuditLogFilters {
  const filters: AuditLogFilters = {};

  const userId = searchParams.get("userId");
  if (userId) filters.userId = userId;

  const type = searchParams.get("type");
  if (type) filters.type = type;

  const actionQuery = searchParams.get("action");
  if (actionQuery) filters.action = actionQuery;

  const success = searchParams.get("success");
  if (success !== null) filters.success = success === "true";

  const ip = searchParams.get("ip");
  if (ip) filters.ip = ip;

  const startDate = searchParams.get("startDate");
  if (startDate) filters.startDate = new Date(startDate);

  const endDate = searchParams.get("endDate");
  if (endDate) filters.endDate = new Date(endDate);

  const page = searchParams.get("page");
  if (page) filters.page = parseInt(page, 10);

  const limit = searchParams.get("limit");
  if (limit) filters.limit = parseInt(limit, 10);

  return filters;
}
