#!/usr/bin/env bash
# Petición firmada a la API de facturas de ToBooky, con curl y openssl.
# Documentación: https://www.tobooky.es/developers/api
#
# Uso: TOBOOKY_KEY=tbk_... TOBOOKY_SECRET=tbs_... bash tobooky_curl.sh
API="${TOBOOKY_URL:-https://www.tobooky.es}"; KEY="$TOBOOKY_KEY"; SECRET="$TOBOOKY_SECRET"
METHOD="POST"; PATH_="/api/v1/invoices-issued"; QUERY=""
BODY='{"client":{"cif":"B12345678","name":"Cliente Demo SL"},"lines":[{"subject":"Consultoría","quantity":2,"unit_price":100,"perc_iva":21}]}'

TS=$(date +%s)
NONCE=$(openssl rand -hex 16)
BODY_HASH=$(printf '%s' "$BODY" | openssl dgst -sha256 -hex | sed 's/^.* //')
TO_SIGN=$(printf 'v1\n%s\n%s\n%s\n%s\n%s\n%s' "$TS" "$NONCE" "$METHOD" "$PATH_" "$QUERY" "$BODY_HASH")
SIG="v1=$(printf '%s' "$TO_SIGN" | openssl dgst -sha256 -hmac "$SECRET" -hex | sed 's/^.* //')"

curl -sS -X "$METHOD" "$API$PATH_" \
  -H "Content-Type: application/json" \
  -H "X-Api-Key: $KEY" -H "X-Api-Timestamp: $TS" -H "X-Api-Nonce: $NONCE" -H "X-Api-Signature: $SIG" \
  -H "Idempotency-Key: pedido-1234" \
  --data-binary "$BODY"
