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

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 });
    }
    if (user.role === "admin" && !user.gymId) {
      return new NextResponse("Admin gymId not set", { status: 400 });
    }

    const url = new URL(req.url);
    const searchParams = url.searchParams;

    let targetGymId: string | null = null;
    if (user.role === "admin") {
      targetGymId = user.gymId ?? null;
    } else if (user.role === "superAdmin") {
      targetGymId = searchParams.get("gymId");
    }

    const allUsers = await db.getAllUsers();
    const allClients = await db.getAllClients();

    const usersById = new Map(allUsers.map((u) => [u.id, u]));
    const filteredUsers = targetGymId
      ? allUsers.filter((u) => u.gymId === targetGymId)
      : allUsers;
    const filteredClients = targetGymId
      ? allClients.filter((c) => {
          const u = usersById.get(c.userId);
          return u?.gymId === targetGymId;
        })
      : allClients;

    const stats = {
      totalUsers: filteredUsers.length,
      activeClients: filteredClients.filter(
        (c) => c.membershipStatus === "active",
      ).length,
      totalRevenue: 0,
      revenueGrowth: 0,
    };

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