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

export const fetchHighlights = async (): Promise<PaginatedDocs<Highlight> | undefined> => {
  const date = new Date();
  date.setHours(0, 0, 0, 0);

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

  const stringifiedQuery = stringify(
    {
      sort: "date",
      where: query,
      limit: 3
    },
    { addQueryPrefix: true },
  )

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