#!/usr/bin/env bash
set -euo pipefail

: "${CIERRELISTO_API_KEY:?Define CIERRELISTO_API_KEY}"
: "${CIERRELISTO_TAXPAYER_ID:?Define CIERRELISTO_TAXPAYER_ID}"

CIERRELISTO_API_URL="${CIERRELISTO_API_URL:-https://sandbox.api.cierrelisto.com}"
CIERRELISTO_EXTERNAL_ID="${CIERRELISTO_EXTERNAL_ID:-sandbox-31-$(date +%s)}"
CIERRELISTO_IDEMPOTENCY_KEY="${CIERRELISTO_IDEMPOTENCY_KEY:-$CIERRELISTO_EXTERNAL_ID}"

curl --fail-with-body --silent --show-error \
  --request POST \
  --url "$CIERRELISTO_API_URL/v1/taxpayers/$CIERRELISTO_TAXPAYER_ID/invoices" \
  --header "Authorization: Bearer $CIERRELISTO_API_KEY" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: $CIERRELISTO_IDEMPOTENCY_KEY" \
  --data @- <<JSON
{
  "external_id": "$CIERRELISTO_EXTERNAL_ID",
  "ecf_type": "31",
  "issue_date": "2026-07-29",
  "due_date": "2026-08-28",
  "currency": "DOP",
  "language": "es",
  "payment_type": "credit",
  "buyer": {
    "legal_name": "CLIENTE DE PRUEBA SRL",
    "tax_id": "131246796",
    "email": "cuentas@cliente.example",
    "address": {
      "line1": "Av. Abraham Lincoln 1001",
      "city": "Santo Domingo de Guzmán",
      "province_or_state": "Distrito Nacional",
      "country_code": "DO"
    }
  },
  "lines": [
    {
      "line_id": "1",
      "description": "Servicios profesionales de julio de 2026",
      "sku": "SERV-CONT-001",
      "unit": "servicio",
      "item_kind": "service",
      "billing_indicator": 1,
      "unit_code": 28,
      "quantity": "1",
      "unit_price": "70000.00",
      "discount": null,
      "taxes": [
        {
          "code": "ITBIS",
          "label": "ITBIS 18%",
          "rate_percent": "18"
        }
      ]
    }
  ],
  "declared_totals": {
    "subtotal": "70000.00",
    "discount_total": "0.00",
    "tax_total": "12600.00",
    "total": "82600.00"
  },
  "payment_terms": "Pago por transferencia dentro de 30 días."
}
JSON
