/**
 * Genre normalization helper — resolves raw genre strings to TMDB genre IDs at ingest time.
 *
 * Two paths:
 *   1. TMDB enrichment: genre objects come directly from TMDB API → use their IDs as-is.
 *   2. Chain scraper: genres arrive as raw name strings (EN/AR/KU) → look up in genre_aliases.
 */

/**
 * Build a comma-separated TMDB genre IDs string from TMDB genre objects.
 * This is the authoritative path — TMDB IDs are stable and require no lookup.
 */
export function genreIdsFromTmdb(
  genres: Array<{ id: number; name: string }> | undefined | null,
): string | null {
  if (!genres?.length) return null;
  const seen = new Set<number>();
  const ids: string[] = [];
  for (const g of genres) {
    if (!seen.has(g.id)) {
      seen.add(g.id);
      ids.push(String(g.id));
    }
  }
  return ids.length ? ids.join(',') : null;
}

/**
 * Resolve a raw comma-separated genre string (from chain scrapers) to TMDB genre IDs
 * via the genre_aliases table. Used before TMDB enrichment runs.
 *
 * Returns null if db unavailable, genres table missing, or no aliases matched.
 */
export async function resolveGenreIds(
  rawGenre: string | null | undefined,
  db: D1Database,
): Promise<string | null> {
  if (!rawGenre) return null;

  const tokens = rawGenre
    .split(',')
    .map((t) => t.trim().toLowerCase())
    .filter(Boolean);

  if (!tokens.length) return null;

  try {
    const placeholders = tokens.map(() => '?').join(',');
    const { results } = await db
      .prepare(`SELECT alias, genre_id FROM genre_aliases WHERE alias IN (${placeholders})`)
      .bind(...tokens)
      .all<{ alias: string; genre_id: string }>();

    const aliasMap = new Map(results.map((r) => [r.alias, r.genre_id]));

    const seen = new Set<string>();
    const ids: string[] = [];
    for (const token of tokens) {
      const id = aliasMap.get(token);
      if (id && !seen.has(id)) {
        seen.add(id);
        ids.push(id);
      }
    }
    return ids.length ? ids.join(',') : null;
  } catch {
    // genre_aliases table may not exist yet
    return null;
  }
}
