// packages/commerce-catalog-react/src/useProductBySlug.tsx
import type { Product, ReadOpts } from '@platform-modules/commerce-catalog'
import { useCatalogContext } from './CatalogProvider.js'
import { useAsyncResource } from './useAsyncResource.js'

export function useProductBySlug(
  slug: string,
  opts?: Partial<ReadOpts>,
  seed?: { initialData?: Product | null },
): { product: Product | null; loading: boolean; error: Error | null; reload: () => void } {
  const { client } = useCatalogContext('useProductBySlug')
  const audience = opts?.audience ?? 'public'
  const readOpts: ReadOpts = { ...opts, audience }
  const key = `slug:${slug}|${audience}|${opts?.vendorId ?? ''}|${opts?.now?.getTime() ?? ''}`
  const fetcher = () => client.getProductBySlug(slug, readOpts)
  const { data, loading, error, reload } = useAsyncResource<Product | null>(fetcher, key, seed)
  return { product: data, loading, error, reload }
}
