// Copyright IBM Corp. 2020, 2025

import debug from 'debug'
import fetch from '@stepzen/fetch'
import {createRequire} from 'node:module'

const {version} = createRequire(import.meta.url)('../../../package.json')

const proxy = async (req, res) => {
  const {adminkey, debugging, zenservUrl, predicates, workspace, accessToken} =
    req.stepzen

  let endpoint = workspace.endpoint

  const headers = {
    Authorization: accessToken ? `Bearer ${accessToken}` : `Apikey ${adminkey}`,
    ...(req.body.headers || {}),
  }
  delete req.body.headers
  if (debugging.enabled) {
    headers = {
      'StepZen-Debug-Level': 1,
      ...headers,
    }
  }

  const url = `${zenservUrl}/${endpoint}/__graphql`

  debug('stepzen:dashboard')(`proxy headers: ${JSON.stringify(headers)}`)
  debug('stepzen:dashboard')(`proxy url: ${url}`)

  const response = await fetch(url, {
    body: JSON.stringify(req.body),
    headers: {
      ...headers,
      'Content-Type': 'application/json',
      'stepzen-cli-version': version,
      'user-agent': `stepzen-cli/${version}`,
    },
    method: 'POST',
  })
  const json = await response.json()

  res.json(json)
}

export default proxy
