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

/**
 * Fetch last announcement for a parish
 */
export const fetchLastAnnouncement = async (parishId: string): Promise<Announcement |  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/announcement${stringifiedQuery}`)
  if (!response.ok) return undefined
  const announcements = await response.json() as PaginatedDocs<Announcement>
  return announcements.docs[0]
}