import { notFound } from 'next/navigation'
import { Parish } from '@/pageComponents/Parish/Parish'
import { fetchEvents } from '@/fetch/events'
import { fetchWorship } from '@/fetch/worship'
import { fetchParish } from '@/fetch/parish'
import { fetchLastAnnouncement } from '@/fetch/announcement'
import { transformGallery } from '@/utils/dto/gallery'
import { fetchLastCalendar } from '@/fetch/calendar'

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

  const slug = (await params).slug;
  const parish = await fetchParish(slug);

  if(!parish || !parish.docs[0]) {
    notFound();
  }

  const {
    id,
    name,
    description,
    history,
    contactPersons,
    contact,
    photo,
    churches,
    gallery
  } = parish.docs[0]
  const events = await fetchEvents({ 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);
  return (
    <Parish
      title={name}
      slug={slug}
      image={typeof photo === "string" ? photo : photo.url || "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}
    />
  )
}