import { createClient } from 'next-sanity'
import imageUrlBuilder from '@sanity/image-url'
import type { SanityImageSource } from '@sanity/image-url/lib/types/types'

export const projectId = 'zal102rv'
export const dataset = 'production'
export const apiVersion = '2024-01-01'

export const client = createClient({
  projectId,
  dataset,
  apiVersion,
  useCdn: false, // false = direct API; avoids CDN DNS issues in dev/server
})

const builder = imageUrlBuilder(client)

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

// ─── GROQ Queries ────────────────────────────────────────────────────────────

/** All published posts for the listing page, newest first */
export const postsQuery = `
  *[_type == "post" && defined(slug.current) && publishedAt <= now()]
  | order(publishedAt desc) {
    _id,
    title,
    slug,
    publishedAt,
    excerpt,
    mainImage { ..., alt },
    "author": author->{ name, image }
  }
`

/** Single post by slug for the detail page */
export const postBySlugQuery = `
  *[_type == "post" && slug.current == $slug][0] {
    _id,
    title,
    slug,
    publishedAt,
    excerpt,
    mainImage { ..., alt },
    body,
    seoTitle,
    seoDescription,
    "author": author->{ name, image, bio }
  }
`

/** All slugs — used for generateStaticParams */
export const postSlugsQuery = `
  *[_type == "post" && defined(slug.current)] { "slug": slug.current }
`

/** All changelog entries — published, newest first */
export const changelogEntriesQuery = `
  *[_type == "changelogEntry" && publishedAt <= now()]
  | order(publishedAt desc) {
    _id, title, version, publishedAt, tags, body
  }
`

/** Roadmap items — excludes shipped, sorted by manual order */
export const roadmapItemsQuery = `
  *[_type == "roadmapItem" && status != "shipped"]
  | order(order asc) {
    _id, title, description, status, order
  }
`
