import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import {
  getLoginHistory,
  getLoginCountries,
  getLoginsByCountry,
  exportLoginHistoryToCSV,
  type LoginHistoryFilters,
} 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 countries
        if (action === "countries") {
          const countries = await convexQuery(
            (api.auth.queries as any).getLoginCountries,
            {},
          );
          return NextResponse.json({ countries: countries ?? [] });
        }

        // Get logins by country
        if (action === "by-country") {
          const days = parseInt(searchParams.get("days") || "30", 10);
          const data = await convexQuery(
            (api.auth.queries as any).getLoginsByCountry,
            { days },
          );
          return NextResponse.json({ data: data ?? [] });
        }

        // Get paginated login history
        const filters = buildFilters(searchParams);
        const result = await convexQuery(
          (api.auth.queries as any).getLoginHistoryAll,
          {
            userId: filters.userId,
            success: filters.success,
            country: filters.country,
            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 login history failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

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

    // Get logins by country for map visualization
    if (action === "by-country") {
      const days = parseInt(searchParams.get("days") || "30", 10);
      const data = await getLoginsByCountry(days);
      return NextResponse.json({ data });
    }

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

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

    // Get paginated login history
    const filters = buildFilters(searchParams);
    const result = await getLoginHistory(filters);

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

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

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

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

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

  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;
}
