import "server-only"

type ErpConfig = {
  baseUrl: string
  user: string
  password: string
}

function getErpConfig(): ErpConfig {
  const baseUrl = process.env.ERP_API_URL
  const user = process.env.ERP_API_USER
  const password = process.env.ERP_API_PASSWORD
  if (!baseUrl || !user || !password) {
    throw new Error("ERP_API_URL/ERP_API_USER/ERP_API_PASSWORD are required")
  }
  return { baseUrl, user, password }
}

async function erpPost<T>(path: string, payload: Record<string, unknown>): Promise<T> {
  const { baseUrl, user, password } = getErpConfig()
  const res = await fetch(`${baseUrl}${path}`, {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      usuario: user,
      senha: password,
      ...payload,
    }),
    cache: "no-store",
  })
  const json = await res.json().catch(() => ({}))
  if (!res.ok || (json as { status?: string })?.status === "erro") {
    const detail =
      (json as { mensagem?: string; message?: string; error?: string })?.mensagem ||
      (json as { mensagem?: string; message?: string; error?: string })?.message ||
      (json as { mensagem?: string; message?: string; error?: string })?.error ||
      JSON.stringify(json)
    throw new Error(`ERP_HTTP_${res.status}: ${detail}`)
  }
  return json as T
}

export async function getClienteByCnpj(cnpj: string) {
  return erpPost<{ status?: string; resultado?: Record<string, unknown> }>(
    "/clientes",
    {
      chamada: "consultaCliente",
      parametros: { cpf_cnpj: cnpj },
    }
  )
}

export async function getContatos(clienteId: string | number) {
  const id = typeof clienteId === "number" ? clienteId : Number(clienteId)
  if (!Number.isFinite(id)) {
    throw new Error("ERP_CLIENT_ID_INVALID")
  }
  return erpPost<{ status?: string; resultado?: Array<Record<string, unknown>> }>(
    "/contatos",
    {
      chamada: "listaContatos",
      parametros: { cliente_id: id },
    }
  )
}
