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

const CACHE_TTL = 300 // 5 minutes

/**
 * Fetch last announcement for a parish
 */
export const fetchLastAnnouncement = async (
  parishId: string,
): Promise<Announcement | 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: 'announcement',
    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 announcement for each parish
 */
export const fetchLastAnnouncements = unstable_cache(
  async (): Promise<Array<{ parish: Parish; doc: Announcement }>> => {
    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 fetchLastAnnouncement(parish.id)
        return doc ? { parish, doc } : null
      }),
    )

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