import { createClient } from "@/lib/supabase/server";
import type { Game } from "@/lib/types";

const GAME_LIST_COLUMNS = "id, slug, title, cover_image, editor_score, price_type";

export async function getHomepageData() {
  const supabase = createClient();

  const { data: config } = await supabase
    .from("homepage_config")
    .select("featured_game_id, row_order")
    .single();

  const { data: featured } = config?.featured_game_id
    ? await supabase.from("games").select("*").eq("id", config.featured_game_id).single()
    : { data: null };

  const { data: collections } = await supabase
    .from("collections")
    .select("id, title, slug, game_ids")
    .order("sort_order", { ascending: true });

  // Resolve each collection's game_ids into card data in one batched query.
  const allIds = Array.from(new Set((collections ?? []).flatMap((c) => c.game_ids)));
  const { data: games } = allIds.length
    ? await supabase.from("games").select(GAME_LIST_COLUMNS).in("id", allIds).eq("status", "published")
    : { data: [] };

  const gamesById = new Map((games ?? []).map((g) => [g.id, g]));
  const rows = (collections ?? []).map((c) => ({
    title: c.title,
    slug: c.slug,
    games: c.game_ids.map((id: string) => gamesById.get(id)).filter(Boolean),
  }));

  return { featured: featured as Game | null, rows };
}

export async function getGameBySlug(slug: string) {
  const supabase = createClient();
  const { data, error } = await supabase
    .from("games")
    .select(
      `*,
      platforms:game_platforms(platform:platforms(id, name, slug, icon_url)),
      genres:game_genres(genre:genres(id, name, slug, icon_url))`
    )
    .eq("slug", slug)
    .eq("status", "published")
    .single();

  if (error || !data) return null;

  return {
    ...data,
    platforms: data.platforms?.map((p: any) => p.platform) ?? [],
    genres: data.genres?.map((g: any) => g.genre) ?? [],
  } as Game;
}

export async function getSimilarGames(game: Game, limit = 6) {
  const supabase = createClient();
  const genreIds = (game.genres ?? []).map((g) => g.id);
  if (!genreIds.length) return [];

  const { data } = await supabase
    .from("games")
    .select(`${GAME_LIST_COLUMNS}, game_genres!inner(genre_id)`)
    .eq("status", "published")
    .neq("id", game.id)
    .in("game_genres.genre_id", genreIds)
    .limit(limit);

  return data ?? [];
}
