import { notFound } from 'next/navigation'
import { EventPage } from '@/pageComponents/Event/Event'
import { getPhoto } from '@/utils/dto/gallery'
import { canView, getRequestAuth } from '@/utils/auth'
import { fetchEventById } from '@/fetch/events'
import { fetchUpcomingOrPastOccurrences } from '@/fetch/eventOccurrences'
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave/RefreshRouteOnSave'
import { eventToPageProps, transformOccurrences } from '@/utils/dto/events'

export default async function Page({ params }: { params: Promise<{ eventId: string }> }) {
  const { eventId } = await params
  const { authenticated, isDraft } = await getRequestAuth()

  const event = await fetchEventById(eventId, isDraft)
  if (!canView(event, authenticated)) notFound()

  const occurrences = await fetchUpcomingOrPastOccurrences({ eventId, limit: 5 })
  const upcomingOccurrences = transformOccurrences(occurrences.docs)
  const photo = getPhoto('tablet', event.photo)

  return (
    <>
      {isDraft && <RefreshRouteOnSave />}
      <EventPage
        {...eventToPageProps(event)}
        photo={photo}
        isAuthenticated={authenticated}
        upcomingOccurrences={upcomingOccurrences}
      />
    </>
  )
}
