/**
 * Cliente TheGamesDB (simple wrapper)
 * - `searchGames(query)`
 * - `getGameById(id)`
 */
import { fetch } from 'undici';

export type MetadataGame = {
  id?: number;
  name: string;
  slug?: string;
  releaseDate?: string;
  genres?: string[];
  platforms?: any[];
  coverUrl?: string;
  source?: string;
};

const API_BASE = 'https://api.thegamesdb.net';

export async function searchGames(query: string): Promise<MetadataGame[]> {
  const key = process.env.THEGAMESDB_API_KEY;
  if (!key) return [];

  try {
    const url = `${API_BASE}/v1/Games/ByGameName?name=${encodeURIComponent(query)}`;
    const res = await fetch(url, { headers: { 'Api-Key': key } });
    if (!res.ok) return [];
    const json = await res.json();
    const games = json?.data?.games ?? {};
    const baseUrl = json?.data?.base_url?.original ?? '';
    const hits: MetadataGame[] = [];
    for (const gid of Object.keys(games)) {
      const g = games[gid];
      hits.push({
        id: Number(gid),
        name: g?.game?.title ?? g?.title ?? String(gid),
        slug: g?.game?.slug ?? undefined,
        releaseDate: g?.game?.release_date ?? undefined,
        genres: Array.isArray(g?.game?.genres) ? g.game.genres.map((x: any) => x.name) : undefined,
        coverUrl: g?.game?.images?.boxart?.[0]?.thumb
          ? `${baseUrl}${g.game.images.boxart[0].thumb}`
          : undefined,
        source: 'thegamesdb',
      });
    }

    return hits;
  } catch (err) {
    // eslint-disable-next-line no-console
    console.debug('thegamesdbClient.searchGames error', err);
    return [];
  }
}

export async function getGameById(id: number): Promise<MetadataGame | null> {
  const key = process.env.THEGAMESDB_API_KEY;
  if (!key) return null;

  try {
    const url = `${API_BASE}/v1/Games/ByGameID?id=${encodeURIComponent(String(id))}`;
    const res = await fetch(url, { headers: { 'Api-Key': key } });
    if (!res.ok) return null;
    const json = await res.json();
    const games = json?.data?.games ?? {};
    const baseUrl = json?.data?.base_url?.original ?? '';
    const firstKey = Object.keys(games)[0];
    const g = games[firstKey];
    if (!g) return null;
    return {
      id: Number(firstKey),
      name: g?.game?.title ?? g?.title ?? String(firstKey),
      slug: g?.game?.slug ?? undefined,
      releaseDate: g?.game?.release_date ?? undefined,
      genres: Array.isArray(g?.game?.genres) ? g.game.genres.map((x: any) => x.name) : undefined,
      coverUrl: g?.game?.images?.boxart?.[0]?.thumb
        ? `${baseUrl}${g.game.images.boxart[0].thumb}`
        : undefined,
      source: 'thegamesdb',
    };
  } catch (err) {
    // eslint-disable-next-line no-console
    console.debug('thegamesdbClient.getGameById error', err);
    return null;
  }
}

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