// Cliente SOAP al worldserver de AzerothCore (port de home/ac_soap.py).
function escapeXml(s: string): string {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
}

/** Ejecuta un comando en el worldserver por SOAP. Devuelve el texto de respuesta o null. */
export async function executeSoapCommand(command: string): Promise<string | null> {
  const url = process.env.AC_SOAP_URL
  const user = process.env.AC_SOAP_USER ?? ''
  const pass = process.env.AC_SOAP_PASSWORD ?? ''
  const urn = process.env.AC_SOAP_URN ?? 'urn:AC'
  if (!url) return null

  const soap = `<?xml version="1.0" encoding="utf-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="${urn}">
  <SOAP-ENV:Body><ns1:executeCommand><command>${escapeXml(command)}</command></ns1:executeCommand></SOAP-ENV:Body>
</SOAP-ENV:Envelope>`

  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        Authorization: 'Basic ' + Buffer.from(`${user}:${pass}`).toString('base64'),
        'Content-Type': 'application/xml',
      },
      body: soap,
      signal: AbortSignal.timeout(5000),
    })
    if (!res.ok) return null
    return await res.text()
  } catch {
    return null // worldserver inaccesible
  }
}
