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

BASE_URL="${BASE_URL:-http://127.0.0.1:8080}"
BASE_URL="${BASE_URL%/}"
temporary_dir="$(mktemp -d)"
trap 'rm -rf "$temporary_dir"' EXIT

check_json_status() {
  local path="$1"
  local expected="$2"
  local output="$temporary_dir/response.json"
  local headers="$temporary_dir/headers.txt"
  curl --fail --silent --show-error --max-time 10 -D "$headers" -o "$output" "$BASE_URL$path"
  grep -qi '^x-request-id:' "$headers"
  grep -q "\"status\":\"$expected\"" "$output"
  echo "通过：$path"
}

check_page() {
  local path="$1"
  local output="$2"
  curl --fail --silent --show-error --max-time 10 -o "$output" "$BASE_URL$path"
  grep -qi '<!doctype html' "$output"
  echo "通过：$path"
}

check_json_status "/api/health" "ok"
check_json_status "/api/ready" "ready"
check_page "/" "$temporary_dir/user.html"
check_page "/login/" "$temporary_dir/admin.html"

admin_asset="$(grep -Eo '/login/assets/[^\" ]+\.(js|css)' "$temporary_dir/admin.html" | head -1)"
test -n "$admin_asset"
curl --fail --silent --show-error --max-time 10 -o /dev/null "$BASE_URL$admin_asset"
echo "通过：后台静态资源 $admin_asset"
echo "生产冒烟检查完成：$BASE_URL"
