import type { Metadata } from 'next';
import { notFound } from 'next/navigation';

import { getCreationList } from '@/services/creations';

import { metaAttributes110 } from '@/utils/filterUtils';
import { parseMapCoordinates } from '@/utils/mapCoordinates';

import GuessGame, { type GuessItem } from '@/app/[locale]/felfedezes/GuessGame';

export const metadata: Metadata = {
  title: 'Hol készült? – játék',
  robots: { index: false, follow: false },
};

// Where a creation was made says the most about buildings and artworks.
const GAME_BRANCHES = metaAttributes110.filter(
  (branch) => branch.key === 'architecture' || branch.key === 'fine'
);
const FIRST_YEAR = 1950;
// More than the five rounds: they come from five different places, and a new game draws from the
// same pool in the browser. The request takes as long for 30 as for 5.
const POOL_SIZE = 30;

async function getItems(): Promise<GuessItem[]> {
  const creations = await getCreationList(
    {
      contentType: GAME_BRANCHES.map((branch) => branch.culturalEntityTypeId),
      withCoord: true,
      imageNeeded: true,
      fromYear: FIRST_YEAR,
      toYear: new Date().getFullYear(),
      random: true,
      maxResults: POOL_SIZE,
    },
    { cache: 'no-store' }
  );
  return creations.flatMap((creation) => {
    const point = parseMapCoordinates(creation.koordinatak);
    const imageId = creation.fokep?.id;
    if (!point || !imageId || !creation.nev || creation.labelYear === null) return [];
    return [
      {
        id: creation.alkotasAzonosito,
        title: creation.nev,
        creator: creation.alkoto.map((person) => person.megjelenitendoNev).join(', ') || null,
        place: creation.telepules,
        category:
          GAME_BRANCHES.find((branch) => branch.culturalEntityTypeId === creation.tipus)?.name ??
          '',
        year: creation.labelYear,
        lat: point.lat,
        lng: point.lng,
        imageId,
      },
    ];
  });
}

// A new pool from the API each time the game is opened; the rounds are drawn in the browser.
export default async function GuessGamePage({ params }: { params: Promise<{ locale: string }> }) {
  if ((await params).locale !== 'hu') notFound();
  return <GuessGame items={await getItems()} />;
}
