// Client-side active-game limit logic: count the caller's active games per kind and test a kind
// against the caller's per-tier cap so the New-Game screen can lock a capped start. The server is
// the source of truth (it refuses a capped create); this only drives the pre-emptive UI lock. Kept
// pure (no DOM / stores) so it unit-tests in the node environment.

import { GameKind, type GameLimits, type GameView } from './model';

/**
 * activeByKind counts the caller's active (status open or in-progress) games per kind. Finished
 * games, local pass-and-play (hotseat) games and untagged games (kind 0, pre-existing) do not
 * count — matching the server's per-kind cap, which is keyed on games.game_kind for open/active
 * games only.
 */
export function activeByKind(games: GameView[]): Record<number, number> {
  const out: Record<number, number> = {};
  for (const g of games) {
    if (g.hotseat) continue;
    if (g.kind === 0) continue;
    if (g.status !== 'active' && g.status !== 'open') continue;
    out[g.kind] = (out[g.kind] ?? 0) + 1;
  }
  return out;
}

/** capFor returns the caller's tier cap for a kind (-1 = unlimited), or -1 when the limits are
 *  absent (an old backend) — the lock then never applies. */
export function capFor(limits: GameLimits | undefined, kind: number): number {
  if (!limits) return -1;
  switch (kind) {
    case GameKind.vsAi:
      return limits.vsAi;
    case GameKind.random:
      return limits.random;
    case GameKind.friends:
      return limits.friends;
    default:
      return -1;
  }
}

/**
 * isKindLocked reports whether the caller has reached its cap for kind, so the New-Game start for
 * that kind is locked. An unlimited cap (-1) or absent limits never lock; a cap of 0 always locks
 * (the kind is disabled for the tier).
 */
export function isKindLocked(games: GameView[], limits: GameLimits | undefined, kind: number): boolean {
  const cap = capFor(limits, kind);
  if (cap < 0) return false;
  return (activeByKind(games)[kind] ?? 0) >= cap;
}
