import { notFound } from 'next/navigation'
import { Event } from '@/payload-types'
import { EventPage } from '@/pageComponents/Event/Event'
import { stringify } from 'qs-esm'
import { getPhoto } from '@/utils/dto/gallery'

export default async function Page({ params }: { params: Promise<{id: string}>}) {

  const id = (await params).id;
  const stringifiedQuery = stringify(
    {
      select: {
        title: true,
        date: true,
        createdAt: true,
        cancelled: true,
        isRecurring: true,
        location: true,
        description: true,
        shortDescription: true,
        contact: true,
        flyer: true,
        photo: true,
        group: true,
        rsvpLink: true
      },
    },
    { addQueryPrefix: true },
  )
  const res = await fetch(`http://localhost:3000/api/event/${id}${stringifiedQuery}`);

  if (!res.ok) {
    notFound()
  }

  const event = await res.json() as Event;
  const group = Array.isArray(event.group) && event.group.length > 0 && typeof event.group[0] == "object" ? event.group[0].slug : undefined;
  const photo = getPhoto("tablet", event.photo);

  return (
    <EventPage
      title={event.title}
      date={event.date}
      createdAt={event.createdAt}
      cancelled={event.cancelled}
      isRecurring={event.isRecurring}
      location={event.location}
      description={event.description}
      shortDescription={event.shortDescription}
      group={group}
      contact={event.contact || undefined}
      rsvpLink={event.rsvpLink || undefined}
      flyer={typeof event.flyer === 'object' ? event.flyer || undefined : undefined}
      photo={photo}
    />
  )
}