import type { H3Event } from 'h3'
import { getRequestHeaders } from 'h3'
import { importMetaClient } from '~~/shared/importMeta'

const PROXY_HEADERS = new Set([
  'x-forwarded-for',
  'x-forwarded-host',
  'x-forwarded-server',
  'x-forwarded-proto',
  'x-forwarded-port',
  'x-client-ip',
  'x-real-ip',
  'x-client-ssl',
  'referer',
  'user-agent',
  'user-agent-https',
  'cookie',
  'authorization',
])

/**
 * Build headers that can be used for proxying requests in fetch requests
 * to API server routes or backend requests.
 *
 * @param event - The request event
 *
 * @returns The request headers appropriate for proxying.
 */
export function buildProxyRequestHeaders(
  event: H3Event,
): Record<string, string> {
  if (importMetaClient) {
    return {}
  }

  const requestHeaders = getRequestHeaders(event)
  const proxyHeaders: Record<string, string> = {}
  for (const name in requestHeaders) {
    if (PROXY_HEADERS.has(name) && requestHeaders[name]) {
      proxyHeaders[name] = requestHeaders[name]
    }
  }

  return proxyHeaders
}
