// API: Custom Page

import { apiVersion, dataset, projectId, useCdn } from 'lib/sanity.api'
import { createClient } from 'next-sanity'

const client = projectId
  ? createClient({
      projectId: process.env.NEXT_PUBLIC_SANITY_PROJECT_ID,
      dataset: process.env.NEXT_PUBLIC_SANITY_DATASET,
      apiVersion: process.env.NEXT_PUBLIC_SANITY_API_VERSION,
      useCdn: true,
      token: process.env.SANITY_API_READ_TOKEN,
    })
  : null

export default async (req, res) => {
  //console.log(req.body.slug)
  const query = `*[_type == "linkGenerate" 
  && 
slug.current == "${req.body.slug}"
]{
  headtitle,
  title,
  coverImage[]{
    "asset":asset->path,
    alt
  },
  contentpages[]->{
    title,
    subtitle,
    coverImage[]{
      "asset":asset->path,
      alt
    },
    content[],
    date
  },
  date
}`

  try {
    const data = await client.fetch(query)
    res.status(200).json(data)
  } catch (error) {
    console.error('Error fetching Sanity data:', error)
    res.status(500).json({ error: 'Error fetching Sanity data' })
  }
}
