import { getPayload, PaginatedDocs } from 'payload'
import config from '@/payload.config'
import { Worship } from '@/payload-types'

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

export const fetchWorship = async (
  args?: FetchWorshipArgs,
): Promise<PaginatedDocs<Worship>> => {
  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 payload = await getPayload({ config })
  return payload.find({
    collection: 'worship',
    sort: 'date',
    where: query,
    select: {
      type: true,
      date: true,
      cancelled: true,
      location: true,
      title: true,
    },
    limit: 100,
  }) as Promise<PaginatedDocs<Worship>>
}

/**
 * Fetch a single worship entry by ID
 */
export async function fetchWorshipById(
  id: string,
): Promise<Worship | undefined> {
  try {
    const payload = await getPayload({ config })
    return await payload.findByID({ collection: 'worship', id })
  } catch {
    return undefined
  }
}
