#!/usr/bin/env bash
# 资质备案管理 API 冒烟测试（需本地服务已启动且已执行 init-v2.sql / 增量脚本）
set -euo pipefail

BASE_URL="${BASE_URL:-http://localhost:8095/safety-eval}"
ORG_INFO_ID="${ORG_INFO_ID:-1}"
CURL_OPTS=(-s -H "orgInfoId: ${ORG_INFO_ID}")

echo "== 1. 创建备案草稿 =="
DRAFT=$(curl "${CURL_OPTS[@]}" -w "\n__HTTP__%{http_code}" -X POST "${BASE_URL}/qual-filing/draft?applyTypeCode=1")
HTTP_CODE="${DRAFT##*__HTTP__}"
BODY="${DRAFT%__HTTP__*}"

if [[ "${HTTP_CODE}" != "200" ]]; then
  echo "HTTP ${HTTP_CODE}"
  echo "${BODY}"
  echo "创建草稿失败：接口返回非 200（401 多为未配置 local 免鉴权，需重启服务）"
  exit 1
fi

FILING_ID=$(echo "$BODY" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['id'])" 2>/dev/null || echo "")
echo "filingId=${FILING_ID}"

if [[ -z "${FILING_ID}" ]]; then
  echo "响应: ${BODY}"
  echo "创建草稿失败：未解析到 filingId，请检查服务与 orgInfoId（当前=${ORG_INFO_ID}）"
  exit 1
fi

echo "== 2. 初始化材料模板 =="
curl "${CURL_OPTS[@]}" -X POST "${BASE_URL}/qual-filing-material/init-template?filingId=${FILING_ID}"
echo

echo "== 3. 暂存备案信息 =="
curl "${CURL_OPTS[@]}" -X POST "${BASE_URL}/qual-filing/save-draft" \
  -H 'Content-Type: application/json' \
  -d "{\"id\":${FILING_ID},\"filingUnitName\":\"测试评价机构\",\"businessScope\":\"安全评价\"}"
echo

echo "== 4. 备案详情 =="
curl "${CURL_OPTS[@]}" "${BASE_URL}/qual-filing/detail?id=${FILING_ID}"
echo

echo "== 5. 备案申请分页 =="
curl "${CURL_OPTS[@]}" "${BASE_URL}/qual-filing/page?current=1&size=10"
echo

echo "完成（提交/审核需材料与承诺书齐全后再测）"
