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'
import { cookies } from 'next/headers'
import { isAuthenticated } from '@/utils/auth'

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 authenticated = await isAuthenticated();

  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
      id={event.id}
      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}
      isAuthenticated={authenticated}
    />
  )
}