#!/usr/bin/env bash
# smoke.sh — end-to-end bring-up + login + parse + export smoke test.
#
# Assumes:
#   - `docker compose up -d` is running.
#   - /etc/cyclone/secrets/admin_pw exists (or CYCLONE_SECRETS_DIR overrides).
#   - The sample 837 at docs/prodfiles/co_medicaid/sample_837p.txt is present.
#
# Override the URL with CYCLONE_SMOKE_URL, the sample path with
# CYCLONE_SMOKE_SAMPLE, the secrets dir with CYCLONE_SECRETS_DIR.
set -euo pipefail

BASE_URL="${CYCLONE_SMOKE_URL:-http://localhost:8080}"
SECRETS_DIR="${CYCLONE_SECRETS_DIR:-/etc/cyclone/secrets}"
ADMIN_PW="$(cat "${SECRETS_DIR}/admin_pw")"
COOKIE_JAR="$(mktemp)"
SAMPLE_837="${CYCLONE_SMOKE_SAMPLE:-docs/prodfiles/co_medicaid/sample_837p.txt}"

cleanup() { rm -f "${COOKIE_JAR}" /tmp/cyclone_smoke_export.zip; }
trap cleanup EXIT

echo "==> waiting for health..."
for i in {1..30}; do
    if curl -fsS "${BASE_URL}/api/health" >/dev/null 2>&1; then break; fi
    sleep 2
    [[ $i -eq 30 ]] && { echo "FAIL: health never came up"; exit 1; }
done
echo "    ok"

echo "==> logging in as admin..."
HTTP_CODE=$(curl -sS -o /dev/null -w '%{http_code}' \
    -c "${COOKIE_JAR}" \
    -H 'Content-Type: application/json' \
    -X POST "${BASE_URL}/api/auth/login" \
    -d "{\"username\":\"admin\",\"password\":\"${ADMIN_PW}\"}")
[[ "${HTTP_CODE}" == "200" ]] || { echo "FAIL: login returned ${HTTP_CODE}"; exit 1; }
echo "    ok (cookie set)"

echo "==> /api/auth/me..."
ME=$(curl -fsS -b "${COOKIE_JAR}" "${BASE_URL}/api/auth/me")
echo "    ${ME}"

if [[ -f "${SAMPLE_837}" ]]; then
    echo "==> parsing sample 837 (${SAMPLE_837})..."
    PARSE=$(curl -fsS -b "${COOKIE_JAR}" -X POST "${BASE_URL}/api/parse-837" \
        -F "file=@${SAMPLE_837}")
    echo "    ${PARSE}" | head -c 200
    echo
else
    echo "==> skipping 837 parse (sample not found at ${SAMPLE_837})"
fi

echo "==> listing batches..."
BATCHES=$(curl -fsS -b "${COOKIE_JAR}" "${BASE_URL}/api/batches")
echo "    ${BATCHES}" | head -c 200
echo

echo "smoke: OK"
