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

/**
 * Fetch a list of events
 *
 */
export async function fetchEvents(parishId: string | undefined, groupId?: string): Promise<PaginatedDocs<Event> | undefined> {
  const date = new Date()

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

  if (parishId) {
    query.and.push({
      "parish": {
        equals: parishId
      },
    })
  }

  if (groupId) {
    query.and.push({
      "group": {
        equals: groupId
      }
    })
  }


  const stringifiedQuery = stringify(
    {
      sort: "date",
      where: query,
      select: {
        location: true,
        date: true,
        title: true,
        cancelled: true
      }
    },
    { addQueryPrefix: true },
  )

  const response = await fetch(`http://localhost:3000/api/event${stringifiedQuery}`)
  if (!response.ok) return undefined
  return response.json()
}
