#!/usr/bin/env bash
# Tiny read-only curl wrapper for the Arcodange Dolibarr API.
#
# Usage:
#   dol-curl.sh <path-with-query>      # e.g. dol-curl.sh /invoices?limit=5
#   dol-curl.sh -i <path>              # include response headers
#   dol-curl.sh -o file.json <path>    # write body to file
#
# Reads DOLIBARR_URL and DOLIBARR_API_KEY from the sibling .env file
# (.claude/skills/dolibarr/.env), mode 600, gitignored.
# Exits non-zero on HTTP >=400 and prints the response body on stderr.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ENV_FILE="${SCRIPT_DIR}/../.env"

if [[ ! -f "${ENV_FILE}" ]]; then
  echo "dol-curl.sh: missing ${ENV_FILE}" >&2
  echo "  Create it with DOLIBARR_URL and DOLIBARR_API_KEY. See dolibarr/README.md." >&2
  exit 2
fi

# shellcheck disable=SC1090
set -a; source "${ENV_FILE}"; set +a

: "${DOLIBARR_URL:?dol-curl.sh: DOLIBARR_URL not set in .env}"
: "${DOLIBARR_API_KEY:?dol-curl.sh: DOLIBARR_API_KEY not set in .env}"

# Last positional arg is the API path; everything before it is passed through to curl.
if [[ $# -lt 1 ]]; then
  echo "dol-curl.sh: missing API path. Example: dol-curl.sh /users/info" >&2
  exit 2
fi

PASSTHRU=()
while [[ $# -gt 1 ]]; do
  PASSTHRU+=("$1")
  shift
done
API_PATH="$1"

# Two-stage call: capture HTTP code + body separately so we can fail clearly
# while still letting the user pipe stdout into jq.
BODY_FILE="$(mktemp -t dolcurl.XXXXXX)"
trap 'rm -f "${BODY_FILE}"' EXIT

HTTP_CODE=$(curl -sS \
  -H "DOLAPIKEY: ${DOLIBARR_API_KEY}" \
  -H "Accept: application/json" \
  --max-time 30 \
  -o "${BODY_FILE}" \
  -w "%{http_code}" \
  ${PASSTHRU[@]+"${PASSTHRU[@]}"} \
  "${DOLIBARR_URL}/api/index.php${API_PATH}")

cat "${BODY_FILE}"
if [[ "${HTTP_CODE}" -ge 400 ]]; then
  echo "dol-curl.sh: HTTP ${HTTP_CODE} on ${API_PATH}" >&2
  exit 1
fi
