import { stringify } from 'qs-esm'
import { PaginatedDocs } from 'payload'
import { Calendar } from '@/payload-types'

/**
 * Fetch last calendar for a parish
 */
export const fetchLastCalendar = async (parishId: string): Promise<Calendar |  undefined> => {
  const date = new Date();
  date.setDate(date.getDate() - 14)

  const query: any = {
    and: [
      {
        parish: {
          equals: parishId
        }
      },
      {
        date: {
          greater_than_equal: date.toISOString(),
        }
      }
    ]

  }

  const stringifiedQuery = stringify(
    {
      sort: "-date",
      where: query,
      limit: 1,
    },
    { addQueryPrefix: true },
  )

  const response = await fetch(`http://localhost:3000/api/calendar${stringifiedQuery}`)
  if (!response.ok) return undefined
  const announcements = await response.json() as PaginatedDocs<Calendar>
  return announcements.docs[0]
}