#!/usr/bin/env bash
# Requiere curl y jq. Ejecución deliberada con datos autorizados.
set -euo pipefail
: "${CFDI_USERNAME:?}" "${CFDI_PASSWORD:?}" "${CFDI_XML_PATH:?}" "${CFDI_IDEMPOTENCY_KEY:?}"
base='https://sandbox-integracfdi.cfdicomplete.com'
# No usar set -x: expone credenciales. JSON por stdin, no por archivo.
auth=$(jq -n --arg username "$CFDI_USERNAME" --arg password "$CFDI_PASSWORD" '{username:$username,password:$password}' | curl --silent --show-error --fail --max-time 120 --proto '=https' "$base/api/v1/auth/token" -H 'Content-Type: application/json' --data-binary @-)
token=$(printf '%s' "$auth" | jq -er '.accessToken')
balance=$(curl --silent --show-error --fail --max-time 120 "$base/api/v1/folios/balance" -H "Authorization: Bearer $token")
# Cuerpo y código en memoria; no --retry ni -L ni archivos de respuesta.
if ! reply=$(curl --silent --show-error --max-time 120 "$base/api/v1/cfdi/stamp" -H "Authorization: Bearer $token" -H 'Content-Type: application/xml' -H "Idempotency-Key: $CFDI_IDEMPOTENCY_KEY" --data-binary "@$CFDI_XML_PATH" --write-out '\n%{http_code}');then
  echo 'Transporte incierto: conservar clave y conciliar sin reenviar' >&2;exit 1
fi
status=$(printf '%s' "$reply" | tail -n 1)
body=$(printf '%s' "$reply" | sed '$d')
case "$status" in
 200) : 'Entregar stampedXml al flujo seguro si existe; no imprimir cuerpo' ;;
 422) : 'Atender código original y mensaje seguro; reserva liberada' ;;
 202) id=$(printf '%s' "$body" | jq -er '.operationId');state=$(curl --silent --show-error --max-time 120 "$base/api/v1/cfdi/operations/$id" -H "Authorization: Bearer $token");;
 *) : 'Distinguir error.code, sin reintento automático';;
esac
unset token auth reply body
