import https from 'https'
import { projectId, dataset, apiVersion } from './sanity'

const SANITY_IP   = '34.102.242.91'
const SANITY_HOST = `${projectId}.api.sanity.io`

export function sanityFetch<T = unknown>(
  query: string,
  params?: Record<string, unknown>
): Promise<T> {
  let path = `/v${apiVersion}/data/query/${dataset}?query=${encodeURIComponent(query)}`
  if (params) {
    for (const [key, value] of Object.entries(params)) {
      path += `&$${key}=${encodeURIComponent(JSON.stringify(value))}`
    }
  }
  return new Promise((resolve, reject) => {
    const req = https.request(
      {
        method: 'GET',
        hostname: SANITY_IP,
        port: 443,
        path,
        servername: SANITY_HOST,
        headers: { Host: SANITY_HOST, Accept: 'application/json', 'User-Agent': 'battl-builders/1.0' },
      },
      (res) => {
        let data = ''
        res.on('data', (c) => (data += c))
        res.on('end', () => {
          try {
            const parsed = JSON.parse(data)
            res.statusCode && res.statusCode >= 400
              ? reject(new Error(`Sanity ${res.statusCode}: ${JSON.stringify(parsed)}`))
              : resolve(parsed.result as T)
          } catch {
            reject(new Error(`Sanity parse error: ${data.slice(0, 200)}`))
          }
        })
      }
    )
    req.on('error', reject)
    req.end()
  })
}
