import { liveQuery } from "dexie";
import { useLiveQuery } from "dexie-react-hooks";
import { GameConfig } from "../types";
import { ImportedGame } from "../types/gameImport";
import { db } from "../database/db";
import { toGameConfig } from "../utils/gameImportAdapter";
import { azulConfig } from "./azul/config";
import { caboConfig } from "./cabo/config";
import { harmonieConfig } from "./harmonie/config";
import { odinCardsConfig } from "./odin_cards/config";
import { skyjoConfig } from "./skyjo/config";

// Built-in games (compiled into the app).
export const games: GameConfig[] = [
  azulConfig,
  caboConfig,
  skyjoConfig,
  harmonieConfig,
  odinCardsConfig,
];

// Imported games for the active profile, kept in sync in-memory so the
// synchronous getGameConfig() below keeps working for non-React callers.
let importedRegistry: GameConfig[] = [];

async function fetchImportedGames(): Promise<ImportedGame[]> {
  const settings = await db.settings.get(1);
  const profileId = settings?.activeProfileId;
  if (!profileId) return [];
  return db.importedGames.where("profileId").equals(profileId).toArray();
}

// Start a background subscription that keeps the in-memory registry current
// across imports and profile switches. Call once at app boot.
export function startGamesRegistry() {
  liveQuery(fetchImportedGames).subscribe({
    next: (rows) => {
      importedRegistry = rows.map(toGameConfig);
    },
    error: (err) => console.error("[games] registry subscription error", err),
  });
}

// Synchronous lookup (built-in + imported). Safe for event handlers / non-React
// code; the registry is populated shortly after boot.
export const getGameConfig = (id: string): GameConfig | undefined =>
  games.find((g) => g.id === id) ?? importedRegistry.find((g) => g.id === id);

// Reactive merged list (built-in + imported for the active profile).
export function useAllGames(): GameConfig[] {
  const imported = useLiveQuery(fetchImportedGames, []);
  return [...games, ...(imported ?? []).map(toGameConfig)];
}

// Reactive single-game lookup.
export function useGameConfig(id: string | undefined): GameConfig | undefined {
  const all = useAllGames();
  return id ? all.find((g) => g.id === id) : undefined;
}
