import { notFound } from 'next/navigation'
import { EventPage } from '@/pageComponents/Event/Event'
import { getPhoto } from '@/utils/dto/gallery'
import { canView, getRequestAuth } from '@/utils/auth'
import {
  fetchOccurrenceById,
  fetchUpcomingOccurrences,
} 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; occurrenceId: string }>
}) {
  const { eventId, occurrenceId } = await params
  const { authenticated, isDraft } = await getRequestAuth()

  const occurrence = await fetchOccurrenceById(occurrenceId, isDraft)
  if (!occurrence) notFound()

  const event = typeof occurrence.event === 'object' ? occurrence.event : undefined
  if (!canView(event, authenticated)) notFound()
  if (event.id !== eventId) notFound()

  const photo = getPhoto('tablet', event.photo)

  const upcomingRaw = await fetchUpcomingOccurrences({
    eventId,
    limit: 5,
    fromDate: new Date(new Date(occurrence.date).getTime() + 1),
  })
  const upcomingOccurrences = transformOccurrences(upcomingRaw.docs)

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