import { NextResponse } from 'next/server';

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

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

import type { TimeMachineItem } from '@/app/[locale]/felfedezes/TimeMachineMap';

// The branches whose creations belong to a place.
const BRANCHES = metaAttributes110.filter((branch) =>
  ['architecture', 'photo', 'fine'].includes(branch.key)
);
const FIRST_YEAR = 1950;

// The Időgép: the creations with a year, a place and a picture, only the fields the block reads,
// from the earliest on. The Java responses come from the fetch cache, so this stays cheap per request.
export async function GET() {
  try {
    // One request, not chunks: with a firstResult above 0 the API leaves out the creators. It
    // fits the 2MB fetch cache for now (1.4MB).
    const creations = await getCreationList({
      contentType: BRANCHES.map((branch) => branch.culturalEntityTypeId),
      imageNeeded: true,
      withCoord: true,
      fromYear: FIRST_YEAR,
      toYear: new Date().getFullYear(),
    });
    const items = creations.flatMap((creation): TimeMachineItem[] => {
      const point = parseMapCoordinates(creation.koordinatak);
      if (!point || !creation.fokep?.id || creation.labelYear === null) return [];
      return [
        {
          id: creation.id,
          alkotasAzonosito: creation.alkotasAzonosito,
          cardType: 'creation',
          nev: creation.nev,
          fokep: {
            id: creation.fokep.id,
            fileName: creation.fokep.fileName,
            version: creation.fokep.version,
          },
          hivatkozas: null,
          hivatkozasLista: null,
          koordinatak: null,
          label: creation.label,
          labelYear: creation.labelYear,
          telepules: creation.telepules,
          alkoto: creation.alkoto.map((person) => ({
            alkotoAzonosito: person.alkotoAzonosito,
            megjelenitendoNev: person.megjelenitendoNev,
            szakma: null,
          })),
          category:
            BRANCHES.find((branch) => branch.culturalEntityTypeId === creation.tipus)?.key ?? '',
          lat: point.lat,
          lng: point.lng,
        },
      ];
    });
    items.sort((a, b) => (a.labelYear as number) - (b.labelYear as number));
    return NextResponse.json({ items });
  } catch (error) {
    reportApiError(error, 'Time map unavailable:');
    return NextResponse.json({ error: 'Time map unavailable' }, { status: 500 });
  }
}
