import { NextResponse } from "next/server";
import { auth } from "@clerk/nextjs/server";
import { getDatabase } from "@/lib/database";
import { ensureUserSynced } from "@/lib/sync-user";

/**
 * GET /api/admin/trainers
 *
 * Admin:
 *   - Lists trainers scoped to the admin's gym (requires admin.gymId).
 *
 * SuperAdmin:
 *   - Optional query param ?gymId=<id> to filter trainers by a specific gym.
 *   - If no gymId provided, returns all trainers across all gyms.
 *
 * Response: Array of trainer users with minimal fields for listing
 */
export async function GET(req: Request) {
  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 });
    }

    const url = new URL(req.url);
    const requestedGymId = url.searchParams.get("gymId");

    // Admins must have a gymId; scope to their gym
    let targetGymId: string | null = null;
    if (user.role === "admin") {
      if (!user.gymId) {
        return new NextResponse("Admin gymId not set", { status: 400 });
      }
      targetGymId = user.gymId as string;
    } else if (user.role === "superAdmin") {
      targetGymId = requestedGymId;
    }

    // Fetch all users and filter to trainers
    const allUsers = await db.getAllUsers();
    let trainers = allUsers.filter((u) => u.role === "trainer");

    // Scope by gym when required/provided
    if (targetGymId) {
      trainers = trainers.filter((t) => t.gymId === targetGymId);
    }

    // Minimal payload suitable for listing
    const payload = trainers.map((t) => ({
      id: t.id,
      email: t.email,
      firstName: t.firstName,
      lastName: t.lastName,
      gymId: t.gymId ?? null,
      createdAt: t.createdAt,
      updatedAt: t.updatedAt,
    }));

    return NextResponse.json(payload);
  } catch (error) {
    console.error("GET /api/admin/trainers error:", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}
