import { getPayload } from 'payload'
import config from '@payload-config'
import { cache } from 'react'

export const getPayloadClient = cache(async () => {
  return await getPayload({ config })
})

export async function getPublishedProducts() {
  const payload = await getPayloadClient()
  const res = await payload.find({
    collection: 'products',
    where: { isPublished: { equals: true } },
    sort: 'sortOrder',
    limit: 100,
    depth: 2,
  })
  return res.docs
}

export async function getProductBySlug(slug: string) {
  const payload = await getPayloadClient()
  const res = await payload.find({
    collection: 'products',
    where: { slug: { equals: slug }, isPublished: { equals: true } },
    limit: 1,
    depth: 2,
  })
  return res.docs[0] ?? null
}

export async function getHomePage() {
  const payload = await getPayloadClient()
  return await payload.findGlobal({ slug: 'homePage', depth: 2 })
}

type MediaLike = {
  url?: string | null
  alt?: string | null
  sizes?: Record<string, { url?: string | null }>
} | string | null | undefined

export function mediaUrl(media: MediaLike, size: 'thumbnail' | 'card' | 'feature' | 'original' = 'original'): string | null {
  if (!media) return null
  if (typeof media === 'string') return media
  if (size !== 'original' && media.sizes?.[size]?.url) return media.sizes[size]!.url!
  return media.url ?? null
}

export function mediaAlt(media: MediaLike, fallback = ''): string {
  if (!media || typeof media === 'string') return fallback
  return media.alt ?? fallback
}
