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

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

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

import YearGame, { type YearItem } from '@/app/[locale]/felfedezes/YearGame';

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

const FIRST_YEAR = 1950;
// More than the five rounds: they come from five different decades, 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;

const branchName = (typeId?: string | null) =>
  metaAttributes110.find((branch) => branch.culturalEntityTypeId === typeId)?.name ?? '';

async function getItems(lastYear: number): Promise<YearItem[]> {
  const creations = await getCreationList(
    {
      contentType: metaAttributes110.map((branch) => branch.culturalEntityTypeId),
      imageNeeded: true,
      fromYear: FIRST_YEAR,
      toYear: lastYear,
      random: true,
      maxResults: POOL_SIZE,
    },
    { cache: 'no-store' }
  );
  return creations.flatMap((creation) => {
    const imageId = creation.fokep?.id;
    const creator = creation.alkoto.map((person) => person.megjelenitendoNev).join(', ');
    if (!imageId || !creation.nev || !creator || creation.labelYear === null) return [];
    return [
      {
        id: creation.alkotasAzonosito,
        title: creation.nev,
        creator,
        place: creation.telepules,
        category: branchName(creation.tipus),
        year: creation.labelYear,
        imageId,
      },
    ];
  });
}

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