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/clients
 *
 * Admin:
 *   - Lists clients scoped to the admin's gym (requires admin.gymId).
 *
 * SuperAdmin:
 *   - Optional query param ?gymId=<id> to filter clients by a specific gym.
 *   - If no gymId provided, returns all clients across all gyms.
 *
 * Response: Array of client users with minimal fields for listing, including membership data.
 */
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;
    } else if (user.role === "superAdmin") {
      targetGymId = requestedGymId;
    }

    // Fetch users and clients
    const allUsers = await db.getAllUsers();
    const usersById = new Map(allUsers.map((u) => [u.id, u]));
    const allClients = await db.getAllClients();

    // Scope clients by gym when provided
    const scopedClients = targetGymId
      ? allClients.filter((c) => {
          const u = usersById.get(c.userId);
          return u?.gymId === targetGymId;
        })
      : allClients;

    // Compose payload merging user and client info
    const payload = scopedClients.map((c) => {
      const u = usersById.get(c.userId);
      return {
        id: c.id,
        userId: c.userId,
        email: u?.email ?? null,
        firstName: u?.firstName ?? null,
        lastName: u?.lastName ?? null,
        gymId: u?.gymId ?? null,
        membershipType: c.membershipType,
        membershipStatus: c.membershipStatus,
        joinDate: c.joinDate,
        lastVisit: c.lastVisit ?? null,
        emergencyContact: c.emergencyContact ?? null,
        createdAt: u?.createdAt ?? null,
        updatedAt: u?.updatedAt ?? null,
      };
    });

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