/**
 * metadataService
 * - `enrichGame({ title, platform? })` -> intenta IGDB, RAWG, TheGamesDB
 */
import * as igdb from './igdbClient';
import * as rawg from './rawgClient';
import * as thegamesdb from './thegamesdbClient';

export type EnrichedGame = {
  source: string;
  externalIds: { igdb?: number; rawg?: number; thegamesdb?: number };
  title: string;
  slug?: string;
  releaseDate?: string;
  genres?: string[];
  coverUrl?: string;
};

function normalize(
  hit: igdb.MetadataGame | rawg.MetadataGame | thegamesdb.MetadataGame
): EnrichedGame {
  const base: EnrichedGame = {
    source: hit.source ?? 'unknown',
    externalIds: {},
    title: hit.name,
    slug: hit.slug,
    releaseDate: hit.releaseDate,
    genres: hit.genres,
    coverUrl: hit.coverUrl,
  };

  if (hit.source === 'igdb' && typeof hit.id === 'number') base.externalIds.igdb = hit.id;
  if (hit.source === 'rawg' && typeof hit.id === 'number') base.externalIds.rawg = hit.id;
  if (hit.source === 'thegamesdb' && typeof hit.id === 'number')
    base.externalIds.thegamesdb = hit.id;

  return base;
}

export async function enrichGame(opts: {
  title: string;
  platform?: string;
}): Promise<EnrichedGame | null> {
  const title = opts?.title;
  if (!title) return null;

  // Prefer IGDB (higher priority)
  try {
    const igdbHits = await igdb.searchGames(title, opts.platform);
    if (igdbHits && igdbHits.length) return normalize(igdbHits[0]);
  } catch (e) {
    // ignore and continue
  }

  try {
    const rawgHits = await rawg.searchGames(title);
    if (rawgHits && rawgHits.length) return normalize(rawgHits[0]);
  } catch (e) {
    // ignore
  }

  try {
    const tgHits = await thegamesdb.searchGames(title);
    if (tgHits && tgHits.length) return normalize(tgHits[0]);
  } catch (e) {
    // ignore
  }

  return null;
}

export default { enrichGame };

/**
 * Metadatos:
 * Autor: GitHub Copilot
 * Última actualización: 2026-02-11
 */
