#!/bin/bash

# 用户管理系统 API 测试脚本

TEST_ADMIN_ACCOUNT="${TEST_ADMIN_ACCOUNT:-admin}"
if [ -z "${TEST_ADMIN_PASSWORD:-}" ]; then
  echo "请先设置 TEST_ADMIN_PASSWORD"
  exit 1
fi

echo "=== 1. 健康检查 ==="
curl http://localhost:8080/health
echo -e "\n"

echo "=== 2. 用户注册 ==="
curl -X POST http://localhost:8080/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{"username":"testuser","password":"Test123456","email":"test@example.com"}'
echo -e "\n"

echo "=== 3. 用户登录（admin） ==="
LOGIN_RESPONSE=$(curl -s -X POST http://localhost:8080/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d "{\"account\":\"${TEST_ADMIN_ACCOUNT}\",\"password\":\"${TEST_ADMIN_PASSWORD}\"}")

echo "$LOGIN_RESPONSE"

# 提取token
TOKEN=$(echo $LOGIN_RESPONSE | grep -o '"access_token":"[^"]*' | cut -d'"' -f4)

echo -e "\n=== 4. 获取用户信息 ==="
if [ -n "$TOKEN" ]; then
    curl -X GET http://localhost:8080/api/v1/auth/userinfo \
      -H "Authorization: Bearer $TOKEN"
    echo -e "\n"
else
    echo "无法获取token，跳过此测试"
fi

echo -e "\n=== 5. 测试限流（连续快速请求） ==="
for i in {1..6}; do
    echo "第 $i 次登录请求："
    curl -s -X POST http://localhost:8080/api/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{"account":"wrong","password":"wrong"}'
    echo ""
done

echo -e "\n测试完成！"
