import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { getDatabase } from "@/lib/database";
import { ensureUserSynced } from "@/lib/sync-user";
import { successResponse } from "@/lib/api/responses";
import { getAttendanceByGym } from "@/lib/gym-context";

export async function GET(req: NextRequest) {
  try {
    const { userId } = await auth();
    if (!userId) return new NextResponse("Unauthorized", { status: 401 });

    const db = await getDatabase();
    const user = await ensureUserSynced(userId, db);

    if (!user || (user.role !== "admin" && user.role !== "superAdmin")) {
      return new NextResponse("Forbidden", { status: 403 });
    }

    // Get target gym based on role
    const url = new URL(req.url);
    const targetGymId =
      user.role === "superAdmin"
        ? (url.searchParams.get("gymId") ?? undefined)
        : (user.gymId ?? undefined);

    // Validate gym access for non-superAdmins
    if (user.role !== "superAdmin" && !targetGymId) {
      return new NextResponse("Forbidden - No gym assigned", { status: 403 });
    }

    // Get attendance filtered by gym
    const attendance = targetGymId
      ? await getAttendanceByGym(targetGymId)
      : await db.getAllAttendance();

    return successResponse({ records: attendance });
  } catch (error) {
    console.error("Admin attendance error:", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
