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

type Args = {
  parishId?: string;
  groupId?: string;
  limit?: number;
  page?: number;
  fromDate?: Date
  toDate?: Date
}


/**
 * Fetch a list of events
 *
 */
export async function fetchEvents(args?: Args): Promise<PaginatedDocs<Event> | undefined> {

  const {parishId, groupId, limit = 30, page = 0, fromDate = new Date(), toDate} = args || {};


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

  if (toDate) {
    query.and.push({
      date: {
        less_than: toDate.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
      },
      depth: 1,
      limit,
      page
    },
    { addQueryPrefix: true },
  )

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