import gamesData from "../../data/games.json";
import userGamesData from "../../data/user-games.json";
import type { Game, SystemId } from "./types";

/**
 * Client-safe catalog snapshot (bundled at build time).
 * Server pages that need live disk state after /contribute uploads
 * should use `@/lib/catalog/server` instead.
 */
const freeGames = gamesData as Game[];
const localGames = userGamesData as Game[];
const games = [...localGames, ...freeGames];

export function getAllGames(): Game[] {
  return games;
}

export function getFreeGames(): Game[] {
  return freeGames;
}

export function getLocalGames(): Game[] {
  return localGames;
}

export function getGameBySlug(slug: string): Game | undefined {
  return games.find((g) => g.slug === slug);
}

export function getGamesBySystem(system: SystemId): Game[] {
  return games.filter((g) => g.system === system);
}

/** Prefer local picks, then a short free list — keeps the top shelf tidy. */
export function getFeaturedGames(): Game[] {
  const localFeatured = localGames.filter((g) => g.featured);
  const freeFeatured = freeGames.filter((g) => g.featured).slice(0, 6);
  const merged = [...localFeatured, ...freeFeatured];
  const seen = new Set<string>();
  return merged.filter((g) => {
    if (seen.has(g.slug)) return false;
    seen.add(g.slug);
    return true;
  });
}

export function searchGames(query: string): Game[] {
  const q = query.trim().toLowerCase();
  if (!q) return games;
  return games.filter(
    (g) =>
      g.title.toLowerCase().includes(q) ||
      g.description.toLowerCase().includes(q) ||
      g.system.includes(q) ||
      (g.author && g.author.toLowerCase().includes(q)),
  );
}

export function getSystemsWithGames(): SystemId[] {
  return [...new Set(games.map((g) => g.system))];
}

export function searchInList(list: Game[], query: string): Game[] {
  const q = query.trim().toLowerCase();
  if (!q) return list;
  return list.filter(
    (g) =>
      g.title.toLowerCase().includes(q) ||
      g.description.toLowerCase().includes(q) ||
      g.system.includes(q) ||
      (g.author && g.author.toLowerCase().includes(q)),
  );
}
