import { db } from "@/server/db";
import { redis } from "@/server/redis";
import { lobbies, lobbyMembers } from "@/server/db/schema";
import { count, eq } from "drizzle-orm";
import { ee } from "@/server/sse";

export async function getLobbyMemberCount(lobbyId: string) {
  // Check if the count is in the cache
  const cachedCount = await redis.get(`lobby:${lobbyId}:memberCount`);
  if (cachedCount !== null) {
    return parseInt(cachedCount, 10);
  }

  // If not in cache, query the database
  const [rawMemberCount] = await db
    .select({ count: count() })
    .from(lobbyMembers)
    .where(eq(lobbyMembers.lobbyId, lobbyId));

  const memberCount = rawMemberCount?.count ?? 0;
  // Cache the result
  await redis.set(`lobby:${lobbyId}:memberCount`, memberCount);
  return memberCount;
}

export async function deleteLobbyIfEmpty(lobbyId: string) {
  const activeMemberCount = await getLobbyMemberCount(lobbyId);
  if (activeMemberCount > 0) return;

  const [realMemberCount] = await db
    .select({ count: count() })
    .from(lobbyMembers)
    .where(eq(lobbyMembers.lobbyId, lobbyId));
  if (realMemberCount?.count === 0) {
    await db.delete(lobbies).where(eq(lobbies.id, lobbyId));
    console.log(`Lobby with ID ${lobbyId} has been deleted. (EMPTY_LOBBY)`);
    // Optionally, remove the cached count
    await redis.del(`lobby:${lobbyId}:memberCount`);
    ee.emit("lobby:update", { id: lobbyId }, true);
  } else {
    console.error(
      "!!!!== Redis Cache is out of sync with the database. ==!!!!",
    );
  }
}

export async function addAdminToLobby(lobbyId: string, playerId: string) {}

export async function handleLobbyAfterLeave(lobbyId: string) {
  await deleteLobbyIfEmpty(lobbyId);
}

export async function decreaseLobbyMemberCount(lobbyId: string) {
  await redis.decr(`lobby:${lobbyId}:memberCount`);
}

export async function increaseLobbyMemberCount(lobbyId: string) {
  await redis.incr(`lobby:${lobbyId}:memberCount`);
}
