import { getPayload } from 'payload'
import config from '@/payload.config'

/**
 * Fetches blog posts based on given criteria.
 *
 * @param {boolean} displayOnFrontpage - Indicates whether to display posts on the front page.
 * @param {number} page - Page number for pagination.
 */
export const fetchBlogPosts = async (displayOnFrontpage: boolean, page: number = 1) => {
  const today = new Date()
  today.setHours(23, 59)

  const query: any = {
    and: [
      {
        '_status': {
          equals: 'published',
        }
      },
      {
        or: [
          {
            'configuration.displayFromDate': {
              equals: null,
            },
          },
          {
            'configuration.displayFromDate': {
              less_than_equal: today.toISOString(),
            },
          },
        ],
      },
      {
        or: [
          {
            'configuration.displayTillDate': {
              equals: null,
            },
          },
          {
            'configuration.displayTillDate': {
              greater_than_equal: today.toISOString(),
            },
          },
        ],
      },
    ],
  }

  if (displayOnFrontpage) {
    query.and.push({
      'configuration.showOnFrontpage': {
        equals: true,
      },
    })
  }

  const payload = await getPayload({ config })
  return payload.find({
    collection: 'blog',
    sort: ['-pinned', '-createdAt'],
    select: {
      title: true,
      date: true,
      photo: true,
      pinned: true,
      content: displayOnFrontpage ? undefined : true,
    },
    where: query,
    limit: 18,
    page,
  })
}

export async function fetchBlog(id: string, draft: boolean) {
  const payload = await getPayload({ config })
  return await payload.findByID({
    collection: 'blog',
    id: id,
    draft,
  })
}