import { notFound } from 'next/navigation'
import { Parish } from '@/pageComponents/Parish/Parish'
import { fetchUpcomingOccurrences } from '@/fetch/eventOccurrences'
import { fetchWorship } from '@/fetch/worship'
import { fetchParish } from '@/fetch/parish'
import { fetchLastAnnouncement } from '@/fetch/announcement'
import { getPhoto, transformGallery } from '@/utils/dto/gallery'
import { fetchLastCalendar } from '@/fetch/calendar'
import { canView, getRequestAuth } from '@/utils/auth'
import { AdminMenu } from '@/components/AdminMenu/AdminMenu'
import { RefreshRouteOnSave } from '@/components/RefreshRouteOnSave/RefreshRouteOnSave'

export default async function ParishPage ({ params }: { params: Promise<{slug: string}>})  {

  const slug = (await params).slug;
  const { authenticated, isDraft } = await getRequestAuth()
  const parish = await fetchParish(slug, isDraft);

  if (!canView(parish, authenticated)) notFound()

  const {
    id,
    name,
    description,
    history,
    contactPersons,
    contact,
    photo,
    churches,
    gallery,
    content
  } = parish
  const events = await fetchUpcomingOccurrences({ parishId: id })
  const churchIds = churches.map(c => typeof c === "string" ? c : c.id)
  const worship = await fetchWorship({ locations: churchIds })
  const announcement = await fetchLastAnnouncement(id);
  const calendar = await fetchLastCalendar(id);
  const image = getPhoto("tablet", photo)
  return (
    <>
      {isDraft && <RefreshRouteOnSave />}
      <Parish
        title={name}
        slug={slug}
        image={image || "notfound"}
        description={description}
        history={history}
        contactPersons={contactPersons || []}
        contact={contact}
        events={events?.docs || []}
        worship={worship?.docs || []}
        announcement={announcement && typeof announcement.document === "object" ? announcement.document.url || undefined : undefined}
        calendar={calendar && typeof calendar.document === "object" ? calendar.document.url || undefined : undefined}
        gallery={gallery ? transformGallery(gallery) : undefined}
        content={content}
      />
      <AdminMenu
        collection={"parish"}
        id={id}
        isAuthenticated={authenticated}
      />
    </>

  )
}