import { defineEventHandler, getHeader, getRequestURL, getRouterParam, proxyRequest, getCookie } from 'h3'
import { useRuntimeConfig } from '#imports'

function joinURL(base: string, path: string) {
  if (!path) return base
  return base.replace(/\/+$/, '') + '/' + path.replace(/^\/+/, '')
}

export default defineEventHandler((event) => {
  const config = useRuntimeConfig()

  // 从 Cookie 读取环境设置，优先于环境变量
  const envCookie = getCookie(event, 'websopy_api_env')
  const isDevEnv = envCookie === 'dev'

  // 开发环境使用本地 9500 端口，生产环境使用配置的环境变量
  const mpApiBase = isDevEnv
    ? 'http://127.0.0.1:9500'
    : (config.public.mpApiBase || 'https://mp-api.websoft.top')

  const path = getRouterParam(event, 'path') || ''
  const search = getRequestURL(event).search
  const target = joinURL(mpApiBase, path) + search

  const tenantId = getHeader(event, 'tenantid') || config.public.tenantId
  const authorization = getHeader(event, 'authorization')

  return proxyRequest(event, target, {
    headers: {
      TenantId: String(tenantId),
      ...(authorization ? { Authorization: String(authorization) } : {})
    }
  })
})
