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

type FetchWorshipArgs = {
  fromDate?: Date,
  tillDate?: Date,
  locations?: string[]
}

export const fetchWorship = async (args?: FetchWorshipArgs): Promise<PaginatedDocs<Worship> | undefined> => {

  const {fromDate, tillDate, locations} = args || {}

  let date = fromDate;
  if (!date) {
    date = new Date();
    date.setHours(0, 0, 0, 0);
  }


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

  if (tillDate) {
    query.and.push({
      date: {
        less_than: tillDate.toISOString()
      }
    })
  }

  if (locations ) {
    query.and.push({
      location: {
        in: locations
      }
    })
  }

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

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