#!/usr/bin/env bash
# Bash + curl 7.76+. Execute no servidor; não habilite set -x com credenciais.
set -euo pipefail
: "${PIX_API_KEY:?Configure PIX_API_KEY}"
: "${PIX_SALE_ID:?Configure PIX_SALE_ID}"
if [[ ! "$PIX_SALE_ID" =~ ^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{21}$ ]]; then
  printf 'PIX_SALE_ID deve ter 21 caracteres Crockford.\n' >&2; exit 1
fi
operation="${1:-}"
if [[ "$operation" != create && "$operation" != get ]]; then
  printf 'Use: bash sale.sh create|get\n' >&2; exit 1
fi
# Persista ID e corpo antes do POST; não troque o ID após um timeout.
url='https://pixlojista.com.br/v1/integration/sales'
args=(--silent --show-error --fail-with-body --max-time 15
  --header "Authorization: Bearer $PIX_API_KEY"
  --header 'Content-Type: application/json')
if [[ "$operation" == create ]]; then
  body=$(printf '{"sale_id":"%s","amount_cents":8990,"reference":"Pedido 1042"}' "$PIX_SALE_ID")
  args+=(--request POST --data "$body")
else
  url="$url/$PIX_SALE_ID"
fi
# Sem redirects. A saída é JSON: sale, brcode, qr_png_base64.
response=$(curl "${args[@]}" --write-out $'\n%{http_code}' "$url")
status="${response##*$'\n'}"
if [[ "$status" != 2?? ]]; then
  printf 'HTTP %s\n' "$status" >&2; exit 1
fi
printf '%s' "${response%$'\n'*}"
printf '\n'
