import { createClient } from '@sanity/client'
import imageUrlBuilder from '@sanity/image-url'

export const sanity = createClient({
  projectId: process.env.SANITY_PROJECT_ID || import.meta.env.SANITY_PROJECT_ID,
  dataset: process.env.SANITY_DATASET || import.meta.env.SANITY_DATASET || 'production',
  apiVersion: '2024-01-01',
  useCdn: false,
})

const builder = imageUrlBuilder(sanity)

export function urlFor(source) {
  return builder.image(source)
}

// ── Queries ────────────────────────────────────────────────────────────────

const PRODUCT_FIELDS = `
  "slug": slug.current,
  name,
  productDisplayName,
  sortOrder,
  index,
  type,
  materials,
  year,
  status,
  description,
  specs,
  notes,
  images,
  "imageAlt": images[0].alt,
  seoTitle,
  seoDescription,
  price,
  currency,
  availability,
  isPublished
`

export async function getPublishedProducts() {
  return sanity.fetch(
    `*[_type == "product" && isPublished == true] | order(sortOrder asc) { ${PRODUCT_FIELDS} }`
  )
}

export async function getProductBySlug(slug) {
  return sanity.fetch(
    `*[_type == "product" && slug.current == $slug && isPublished == true][0] { ${PRODUCT_FIELDS} }`,
    { slug }
  )
}

export async function getHomePage() {
  return sanity.fetch(
    `*[_type == "homePage" && _id == "homePage"][0] {
      heroLabel,
      heroTitle,
      heroSubtitle,
      heroStatus,
      heroImage,
      "heroImageAlt": heroImage.alt,
      collectionLabel,
      collectionCta,
      contactLabel,
      contactTitle,
      contactDescription,
      whatsappNumber,
      whatsappButtonText,
      contactResponseTime,
      footerText,
      instagramUrl,
      seoTitle,
      seoDescription
    }`
  )
}
