import { NextResponse } from 'next/server';

import { getCreatorBirthdaysByRange } from '@/services/creators';

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

// A leap year, so that the creators born on 29 February are included.
const FROM_DATE = '20240101';
const TO_DATE = '20241231';

// "Ön kivel született egy napon?": the creators of the whole year by "month-day", only the fields
// the block reads. The Java response comes from the fetch cache, so this stays cheap per request.
export async function GET() {
  try {
    // The range never moves here, so the day-long default cache lets new creators appear.
    const days = await getCreatorBirthdaysByRange({ fromDate: FROM_DATE, toDate: TO_DATE }, {});
    const people = Object.fromEntries(
      days
        .filter((day) => day.alkotok.length > 0)
        .map((day) => {
          const [, month, date] = day.dateIso.split('-').map(Number);
          return [
            `${month}-${date}`,
            day.alkotok
              .map((creator) => ({
                id: creator.alkotoAzonosito,
                name: creator.nev,
                profession: creator.szakma || null,
                image: creator.imgId,
                // No date in this response: the cards only mark that the creator has died.
                died: creator.elhunyt ? 'elhunyt' : null,
              }))
              .sort((a, b) => a.name.localeCompare(b.name, 'hu')),
          ];
        })
    );
    return NextResponse.json({ people });
  } catch (error) {
    reportApiError(error, 'Creator birthdays unavailable:');
    return NextResponse.json({ error: 'Creator birthdays unavailable' }, { status: 500 });
  }
}
