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

BASE_URL="${BASE_URL:-https://api.tooeasy.mixtech.dev.br}"
JWT_TOKEN="${JWT_TOKEN:-eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImVtYWlsIjoiYWRtaW5AbHVteW9uLnRlY2giLCJpYXQiOjE3NjQ3MzA3MDgsImV4cCI6MTc2NDczNDMwOH0.K9_CVk5zwffHj8OYrjaC4wxHvfHMYS0JCOfX3Sm6-lA}"
PAYLOAD_FILE="${1:-}"

usage() {
    cat <<'USAGE'
Usage: JWT_TOKEN=<token> ./cpr_create.sh <payload.json>

Environment variables:
  BASE_URL   Base URL of the API (default: https://api.tooeasy.mixtech.dev.br)
  JWT_TOKEN  Bearer token used for Authorization header (required)

Arguments:
  <payload.json>  Optional path to the JSON payload body. If omitted, a template is used.
USAGE
}

if [[ -z "$JWT_TOKEN" ]]; then
    echo "[error] JWT_TOKEN environment variable must be set" >&2
    usage
    exit 1
fi

API_ENDPOINT="$BASE_URL/cpr/create"

if [[ -n "$PAYLOAD_FILE" ]]; then
    if [[ ! -f "$PAYLOAD_FILE" ]]; then
        echo "[error] Payload file '$PAYLOAD_FILE' not found" >&2
        exit 1
    fi
    PAYLOAD_CONTENT=$(<"$PAYLOAD_FILE")
else
    read -r -d '' PAYLOAD_CONTENT <<'JSON' || true
{
  "cpr_type_code": "TEMPLATE",
  "cpr_otc_register_account_code": "REG-001",
  "cpr_otc_payment_agent_account_code": "PAY-001",
  "cpr_otc_custodian_account_code": "CUS-001",
  "cpr_internal_control_number": "ICN-0001",
  "cpr_electronic_emission_indicator": "Y",
  "cpr_isin_code": "BR1234567890",
  "cpr_issue_date": "2024-01-01",
  "cpr_maturity_date": "2025-01-01",
  "cpr_issue_quantity": "1000",
  "cpr_issue_value": "500000",
  "cpr_issue_financial_value": "500000",
  "cpr_unit_value": "500",
  "cpr_reference_date": "2024-01-01",
  "cpr_profitability_start_date": "2024-02-01",
  "cpr_automatic_expiration_indicator": "N",
  "cpr_collateral_type_code": "COLL",
  "cpr_collateral_type_name": "Collateral",
  "cpr_constitution_process_indicator": "MANUAL",
  "cpr_otc_bondsman_account_code": "BOND-001",
  "cpr_collaterals_document_number": "DOC-COLL-123",
  "cpr_product_name": "Soy",
  "cpr_product_class_name": "Grain",
  "cpr_product_harvest": "2024",
  "cpr_product_description": "Template product description",
  "cpr_product_quantity": "100",
  "cpr_measure_unit_name": "TON",
  "cpr_packaging_way_name": "Bulk",
  "cpr_product_status_code": "READY",
  "cpr_production_type_code": "AGR",
  "cpr_issuer_name": "Issuer Name",
  "cpr_finality_code": "FIN",
  "cpr_ipoc_code": "IPO-001",
  "cpr_calculation_type_code": "SIMPLE",
  "cpr_initial_exchange_value": "10000",
  "cpr_fixing_type_code": "FIXED",
  "cpr_data_source_type_code": "MANUAL",
  "cpr_adjustment_frequency_type_code": "ANNUAL",
  "cpr_adjustment_pro_rata_type_code": "DAY",
  "cpr_adjustment_type_code": "FIXED",
  "cpr_creditor_name": "Creditor",
  "cpr_ballast_type_code": "BAL",
  "cpr_lot_number": "LOT-001",
  "cpr_ballast_quantity": "100",
  "cpr_currency_code": "BRL",
  "cpr_transaction_identification": "TRX-001",
  "cpr_additional_text": "Additional notes",
  "cpr_number": "CPR-001",
  "cpr_contract_number": "CONT-001",
  "cpr_event_type_code": "EVT",
  "cpr_event_original_date": "2024-01-01",
  "cpr_unit_price_value": "5000",
  "cpr_interest_unit_price_value": "100",
  "cpr_residual_value": "10000",
  "cpr_amortization_percentage": "10",
  "cpr_event_quantity": "1",
  "cpr_production_place_name": "Farm",
  "cpr_property_registration_number": "REG-123",
  "cpr_notary_name": "Notary",
  "cpr_total_production_area_in_hectares_number": "100",
  "cpr_total_area_in_hectares_number": "120",
  "cpr_car_code": "CAR-123",
  "cpr_latitude_code": "-23.5505",
  "cpr_longitude_code": "-46.6333",
  "cpr_zip_code": "01000-000",
  "cpr_green_cpr_indicator": "N",
  "cpr_green_cpr_certificate_name": "Certificate",
  "cpr_green_cpr_certificate_cnpj_number": "12.345.678/0001-99",
  "cpr_green_cpr_georeferencing_description": "Geo desc",
  "cpr_green_cpr_declaration_indicator": "N",
  "cpr_document_deadline_days_number": "30",
  "cpr_place_name": "São Paulo",
  "cpr_guarantee_limit_type_code": "GLT",
  "cpr_mother_code": "MOM-001",
  "cpr_issuers_person_type_acronym": "PJ",
  "cpr_issuers_state_acronym": "SP",
  "cpr_issuers_city_name": "São Paulo",
  "cpr_issuers_ibge_code": "3550308",
  "cpr_issuer_legal_nature_code": "2046",
  "cpr_otc_favored_account_code": "FAV-001",
  "cpr_issuers_document_number": "12345678000199",
  "cpr_deposit_person_type_acronym": "PJ",
  "cpr_self_number": "SELF-001",
  "cpr_settlement_modality_type_code": "CASH",
  "cpr_otc_settlement_bank_account_code": "SET-001",
  "cpr_deposit_quantity": "100",
  "cpr_deposit_unit_price_value": "5000",
  "cpr_payment_method_code": "PIX",
  "cpr_index_code": "CDI",
  "cpr_index_short_name": "CDI",
  "cpr_vcp_indicator_type_code": "VAR",
  "cpr_indexador_percentage_value": "10",
  "cpr_interest_rate_spread_percentage": "2",
  "cpr_interest_rate_criteria_type_code": "SIMPLE",
  "cpr_interest_payment_date": "2024-07-01",
  "cpr_interest_payment_value": "10000",
  "cpr_interest_payment_frequency_code": "ANNUAL",
  "cpr_interest_months_quantity": "12",
  "cpr_interestPaymentFlow_time_unit_type_code": "MONTH",
  "cpr_interestPaymentFlow_deadline_type_code": "FIXED",
  "cpr_payment_start_date": "2024-02-01",
  "cpr_amortization_type_code": "LINEAR",
  "cpr_amortization_months_quantity": "12",
  "cpr_amortizationPaymentFlow_time_unit_type_code": "MONTH",
  "cpr_amortizationPaymentFlow_deadline_type_code": "FIXED",
  "cpr_amortization_start_date": "2024-03-01",
  "cpr_scr_type_code": "SCR",
  "cpr_scr_customer_detail": "Customer detail",
  "cpr_scr_person_type_acronym": "PJ",
  "cpr_deposit_document_number": "DEP-123456",
  "cpr_scr_document_number": "SCR-123456",
  "cpr_creditor_document_number": "CRED-123456",
  "cpr_contract_code": "CON-001",
  "cpr_operation_modality_type_code": "CRED",
  "cpr_bacen_reference_code": "12345",
  "cpr_deliveryPlace_state_acronym": "SP",
  "cpr_deliveryPlace_city_name": "São Paulo",
  "cpr_deliveryPlace_ibge_code": "3550308",
  "cpr_children_codes": ["CHD-001", "CHD-002"]
}
JSON
fi

echo "[info] Sending CPR payload '${PAYLOAD_FILE:-template}' to $API_ENDPOINT"

response_body=$(mktemp)
trap 'rm -f "$response_body"' EXIT

http_code=$(curl --show-error --silent \
    -o "$response_body" \
    -w "%{http_code}" \
    -X POST "$API_ENDPOINT" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $JWT_TOKEN" \
    --data "$PAYLOAD_CONTENT")

if [[ "$http_code" =~ ^2 ]]; then
    jq . <"$response_body"
else
    echo "[error] Request failed with status $http_code" >&2
    cat "$response_body" >&2
    exit 1
fi
