import { getDatabase } from "@/lib/database";

/**
 * Get users filtered by gym ID
 *
 * @param gymId - Gym ID to filter by (undefined returns all users for superAdmin)
 * @returns Array of users in the gym
 */
export async function getUsersByGym(gymId?: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();

  if (!gymId) {
    return allUsers;
  }

  return allUsers.filter((u) => u.gymId === gymId);
}

/**
 * Get clients filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of clients in the gym
 */
export async function getClientsByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();
  const allClients = await db.getAllClients();

  const gymClientUserIds = allUsers
    .filter((u) => u.gymId === gymId && u.role === "client")
    .map((u) => u.id);

  if (gymClientUserIds.length === 0) {
    return [];
  }

  return allClients.filter((c) => gymClientUserIds.includes(c.userId));
}

/**
 * Get trainers filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of trainers in the gym
 */
export async function getTrainersByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();

  return allUsers.filter((u) => u.gymId === gymId && u.role === "trainer");
}

/**
 * Get attendance filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of attendance records in the gym
 */
export async function getAttendanceByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();
  const allAttendance = await db.getAllAttendance();

  const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);

  if (gymUserIds.length === 0) {
    return [];
  }

  return allAttendance.filter((a) => gymUserIds.includes(a.userId));
}

/**
 * Get recommendations filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of recommendations in the gym
 */
export async function getRecommendationsByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();
  const allRecommendations = await db.getAllRecommendations();

  const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);

  if (gymUserIds.length === 0) {
    return [];
  }

  return allRecommendations.filter((r) => gymUserIds.includes(r.userId));
}

/**
 * Get fitness profiles filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of fitness profiles in the gym
 */
export async function getFitnessProfilesByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();
  const allProfiles = await db.getAllFitnessProfiles();

  const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);

  if (gymUserIds.length === 0) {
    return [];
  }

  return allProfiles.filter((p) => gymUserIds.includes(p.userId));
}

/**
 * Get fitness goals filtered by gym ID
 *
 * @param gymId - Gym ID to filter by
 * @returns Array of fitness goals in the gym
 */
export async function getFitnessGoalsByGym(gymId: string) {
  const db = await getDatabase();
  const allUsers = await db.getAllUsers();

  const gymUserIds = allUsers.filter((u) => u.gymId === gymId).map((u) => u.id);

  if (gymUserIds.length === 0) {
    return [];
  }

  const allGoals: any[] = [];
  for (const userId of gymUserIds) {
    const goals = await db.getFitnessGoalsByUserId(userId);
    allGoals.push(...goals);
  }

  return allGoals.sort(
    (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
  );
}

/**
 * Get user by ID and check if they belong to a specific gym
 */
export async function getUserGymId(userId: string): Promise<string | null> {
  const db = await getDatabase();
  const user = await db.getUserById(userId);
  return user?.gymId ?? null;
}
