import { getPayload, PaginatedDocs } from 'payload'
import config from '@/payload.config'
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>> {
  const {
    parishId,
    groupId,
    limit = 30,
    page = 0,
    fromDate = new Date(),
    toDate,
  } = args || {}

  const query: any = {
    and: [
      {
        '_status': {
          equals: 'published',
        }
      },
      {
        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 payload = await getPayload({ config })
  return payload.find({
    collection: 'event',
    sort: 'date',
    where: query,
    select: {
      location: true,
      date: true,
      title: true,
      cancelled: true,
    },
    depth: 1,
    limit,
    page,
  }) as Promise<PaginatedDocs<Event>>
}

/**
 * Fetch a single event by ID
 */
export async function fetchEventById(
  id: string,
  draft: boolean = false,
): Promise<Event | undefined> {
  try {
    const payload = await getPayload({ config })
    return await payload.findByID({ collection: 'event', id, draft })
  } catch {
    return undefined
  }
}
