import { getPayload } from 'payload'
import { unstable_cache } from 'next/cache'
import config from '@/payload.config'
import { Calendar, Parish } from '@/payload-types'

const CACHE_TTL = 300 // 5 minutes

/**
 * Fetch last calendar for a parish
 */
export const fetchLastCalendar = async (
  parishId: string,
): Promise<Calendar | undefined> => {
  const date = new Date()
  date.setDate(date.getDate() - 14)
  const tomorrow = new Date()
  tomorrow.setDate(tomorrow.getDate() + 1)
  tomorrow.setHours(23, 59, 59, 59)

  const payload = await getPayload({ config })
  const result = await payload.find({
    collection: 'calendar',
    sort: '-date',
    where: {
      and: [
        {
          parish: {
            equals: parishId,
          },
        },
        {
          date: {
            greater_than_equal: date.toISOString(),
          },
        },
        {
          date: {
            less_than_equal: tomorrow.toISOString(),
          },
        },
      ],
    },
    limit: 1,
  })
  return result.docs[0]
}

/**
 * Fetch the last calendar for each parish
 */
export const fetchLastCalendars = unstable_cache(
  async (): Promise<Array<{ parish: Parish; doc: Calendar }>> => {
    const payload = await getPayload({ config })
    const parishes = await payload.find({ collection: 'parish', limit: 100 })

    const results = await Promise.all(
      parishes.docs.map(async (parish) => {
        const doc = await fetchLastCalendar(parish.id)
        return doc ? { parish, doc } : null
      }),
    )

    return results.filter(
      (r): r is { parish: Parish; doc: Calendar } => !!r,
    )
  },
  ['fetchLastCalendars'],
  { revalidate: CACHE_TTL },
)
