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

API_BASE="${API_BASE:-http://localhost:3002/api}"
ADMIN_USER="${ADMIN_USER:-admin}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-Admin@123}"
STAFF_USER="${STAFF_USER:-warehouse01}"
STAFF_PASSWORD="${STAFF_PASSWORD:-}"

require_success() {
  local response="$1"
  printf '%s' "$response" | node -e "let value='';process.stdin.on('data',chunk=>value+=chunk).on('end',()=>{const body=JSON.parse(value);if(body.success!==true)process.exit(1)})"
}

status_code() {
  curl -sS -o /tmp/stockflow-smoke-response.json -w '%{http_code}' "$@"
}

echo "Smoke test API: ${API_BASE}"
health="$(curl -sS "${API_BASE%/api}/health")"
require_success "$health"
echo "✓ health"

admin_login="$(curl -sS -X POST "$API_BASE/auth/login" -H 'Content-Type: application/json' -d "{\"username\":\"$ADMIN_USER\",\"password\":\"$ADMIN_PASSWORD\"}")"
require_success "$admin_login"
admin_token="$(printf '%s' "$admin_login" | node -e "let value='';process.stdin.on('data',chunk=>value+=chunk).on('end',()=>process.stdout.write(JSON.parse(value).data.token))")"
echo "✓ admin login"

for endpoint in '/dashboard/summary' '/products-paged?page=1&page_size=2' '/inventory-paged?page=1&page_size=2' '/audit-logs?page=1&page_size=5' '/reports/stock-balance?from=2026-09-01&to=2026-09-30' '/reports/debt-opening?fiscal_year=2026' '/reports/receivables?from=2026-09-01&to=2026-09-30' '/reports/payables?from=2026-09-01&to=2026-09-30'; do
  response="$(curl -sS -H "Authorization: Bearer $admin_token" "$API_BASE$endpoint")"
  require_success "$response"
  echo "✓ admin ${endpoint}"
done
invalid_report_status="$(status_code -H "Authorization: Bearer $admin_token" "$API_BASE/reports/stock-balance?from=2026-02-30&to=2026-03-01")"
if [[ "$invalid_report_status" != "400" ]]; then
  echo "Invalid report date returned HTTP ${invalid_report_status}, expected 400." >&2
  exit 1
fi
echo "✓ report date validation"

if [[ -n "$STAFF_PASSWORD" ]]; then
  staff_login="$(curl -sS -X POST "$API_BASE/auth/login" -H 'Content-Type: application/json' -d "{\"username\":\"$STAFF_USER\",\"password\":\"$STAFF_PASSWORD\"}")"
  require_success "$staff_login"
  staff_token="$(printf '%s' "$staff_login" | node -e "let value='';process.stdin.on('data',chunk=>value+=chunk).on('end',()=>process.stdout.write(JSON.parse(value).data.token))")"
  staff_status="$(status_code -H "Authorization: Bearer $staff_token" "$API_BASE/audit-logs?page=1&page_size=5")"
  if [[ "$staff_status" != "403" ]]; then
    echo "Staff audit-log request returned HTTP ${staff_status}, expected 403." >&2
    exit 1
  fi
  echo "✓ staff permission boundary"
else
  echo "- staff permission boundary skipped (set STAFF_PASSWORD to enable)"
fi

echo "API smoke test passed."
