import { NextRequest, NextResponse } from "next/server";
import { validateStaffSession } from "@/lib/staff-session";
import { getSecurityStats } 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 });
    }

    // --- Convex path ---
    if (getDataSource("auth") === "convex") {
      try {
        const stats = await convexQuery(
          (api.auth.queries as any).getSecurityStats,
          {},
        );
        return NextResponse.json(stats);
      } catch (convexErr) {
        console.error(
          "Convex security stats failed, falling back to Prisma:",
          convexErr,
        );
      }
    }

    // --- Prisma path ---
    const stats = await getSecurityStats();

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