import { htmlToPdfParagraphs, normalizePdfText } from '@/components/pdf/pdfUtils';
import { getEventTimeIntervalString } from '@/utils/eventHelpers';

import { Event, EventInstitutionField } from '@/types/Events';

type BuildEventPdfItemsOptions = {
  getLocationString: (institutionField: EventInstitutionField) => string | null;
  locale: string;
};

export type EventPdfPerson = {
  id: number;
  name: string;
  profession?: string | null;
  url: string;
};

export type EventPdfItem = {
  descriptionParagraphs: string[];
  id: number;
  infoUrl: string | null;
  location: string | null;
  persons: EventPdfPerson[];
  ticketUrl: string | null;
  timeLabel: string;
  title: string;
};

export const buildEventPdfItems = (
  events: Event[],
  { getLocationString, locale }: BuildEventPdfItemsOptions
): EventPdfItem[] =>
  events.map((event) => {
    const institutionField = event.intezmeny?.[0];
    const persons = [...(event.szemely ?? [])]
      .sort((a, b) => a.szemely.name.localeCompare(b.szemely.name))
      .map((person) => ({
        id: person.id,
        name: person.szemely.name,
        profession: person.szemely.szakma?.name,
        url: `https://azopus.hu/alkoto/${person.szemely.alkotoAzonosito}`,
      }));

    return {
      descriptionParagraphs: htmlToPdfParagraphs(event.leiras),
      id: event.id,
      infoUrl: event.infoUrl,
      location: institutionField ? getLocationString(institutionField) : null,
      persons,
      ticketUrl: event.jegyUrl,
      timeLabel: getEventTimeIntervalString(event, true, locale),
      title: normalizePdfText(event.nev),
    };
  });
