import type { Metadata } from 'next';

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

import { CreationListItem } from '@/types/Creation';

import CreationListClient from '@/app/[locale]/alkotasok/CreationListClient';

export const revalidate = 259200; // 3 days in seconds

const CHUNK_SIZE = 3000;

export default async function CreationsWithImagesListPage({
  params,
}: {
  params: Promise<{ locale: string }>;
}) {
  const { locale } = await params;

  const chunksCount = 6;

  const offsets = Array.from({ length: chunksCount }, (_, i) => i * CHUNK_SIZE);

  const chunks = await Promise.all(
    offsets.map((o) =>
      getCreationList({
        firstResult: o,
        maxResults: CHUNK_SIZE,
        imageNeeded: true,
        featuredContent: locale === 'en',
      })
    )
  );

  const creations = chunks.flat().filter(Boolean);

  // Extract and process years
  const years = creations
    .map((c: CreationListItem) => c.labelYear)
    .filter((year: number | null): year is number => typeof year === 'number' && year !== 1000);

  const maxYear = years.length > 0 ? Math.max(...years) : new Date().getFullYear();
  const minYear = years.length > 0 ? Math.min(...years) : maxYear - 100;

  // Get unique years sorted descending (newest first)
  const availableYears: number[] = [...new Set<number>(years)].sort((a, b) => b - a);

  return (
    <CreationListClient
      creations={creations}
      min={minYear}
      max={maxYear}
      initialYear={maxYear}
      availableYears={availableYears}
      showCreatorProfession
    />
  );
}

// ------ META DATA ------
export async function generateMetadata(): Promise<Metadata> {
  return {
    title: 'Alkotások képekkel',
    // description: ,
    alternates: {
      canonical: '/alkotasok-kepekkel',
    },
  };
}
