import { NextResponse } from 'next/server';

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

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

const FIRST_YEAR = 1930;
// Two full rows of eight on a wide screen. A few more are asked for, as a creation without a
// title is left out, so the rows stay full.
const PICTURES = 16;
const ASKED = PICTURES + 4;

// "Mi készült az Ön születési évében?": a day's random pictures of a year, only the fields the
// block reads. The Java responses come from the fetch cache, so this stays cheap per request.
export async function GET(request: Request) {
  const year = Number(new URL(request.url).searchParams.get('year'));
  if (!Number.isInteger(year) || year < FIRST_YEAR || year > new Date().getFullYear()) {
    return NextResponse.json({ error: 'Invalid year' }, { status: 400 });
  }
  try {
    const creations = await getCreationList({
      contentType: metaAttributes110.map((branch) => branch.culturalEntityTypeId),
      imageNeeded: true,
      fromYear: year,
      toYear: year,
      random: true,
      maxResults: ASKED,
    });
    return NextResponse.json({
      items: creations
        .flatMap((creation) =>
          creation.fokep?.id && creation.nev
            ? [
                {
                  id: creation.alkotasAzonosito,
                  title: creation.nev,
                  year,
                  image: creation.fokep.id,
                  creator:
                    creation.alkoto.map((person) => person.megjelenitendoNev).join(', ') || null,
                },
              ]
            : []
        )
        .slice(0, PICTURES),
    });
  } catch (error) {
    reportApiError(error, 'Birth year creations unavailable:');
    return NextResponse.json({ error: 'Birth year creations unavailable' }, { status: 500 });
  }
}
