#!/bin/bash

# 项目创建功能测试 - 简化版
BASE_URL="http://localhost:8080"

echo "=========================================="
echo "项目创建功能测试"
echo "=========================================="

# 1. 登录获取Token
echo "[1/5] 登录获取Token..."
TOKEN_RESPONSE=$(curl -s -X POST "$BASE_URL/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin123"}')

TOKEN=$(echo "$TOKEN_RESPONSE" | grep -o '"token":"[^"]*"' | sed 's/"token":"//;s/"//')

if [ -z "$TOKEN" ]; then
  echo "✗ 登录失败"
  echo "响应: $TOKEN_RESPONSE"
  exit 1
fi

echo "✓ Token获取成功"
echo "Token: ${TOKEN:0:50}..."

# 2. 测试创建项目成功
echo ""
echo "[2/5] 测试创建项目成功..."
PROJECT_NAME="测试项目_$(date +%Y%m%d_%H%M%S)"
REQUEST_DATA="{\"projectName\":\"$PROJECT_NAME\",\"description\":\"测试集成流水分析平台\",\"configType\":\"default\"}"

echo "请求数据: $REQUEST_DATA"

RESPONSE=$(curl -s -X POST "$BASE_URL/ccdi/project" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d "$REQUEST_DATA")

echo "响应: $RESPONSE"

# 检查是否成功
if echo "$RESPONSE" | grep -q '"code":200'; then
  echo "✓ 项目创建成功"

  # 检查lsfxProjectId
  if echo "$RESPONSE" | grep -q '"lsfxProjectId"'; then
    LSFX_ID=$(echo "$RESPONSE" | grep -o '"lsfxProjectId":[0-9]*' | sed 's/"lsfxProjectId"://')
    echo "✓ 流水分析平台项目ID: $LSFX_ID"
  else
    echo "✗ 流水分析平台项目ID缺失"
  fi
else
  echo "✗ 项目创建失败"
fi

# 3. 测试参数校验
echo ""
echo "[3/5] 测试参数校验（空项目名称）..."
REQUEST_DATA='{"projectName":"","description":"测试","configType":"default"}'

RESPONSE=$(curl -s -X POST "$BASE_URL/ccdi/project" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d "$REQUEST_DATA")

if echo "$RESPONSE" | grep -q '"code":200'; then
  echo "✗ 未正确验证参数"
else
  echo "✓ 正确拒绝了空项目名称"
fi

# 4. 测试查询项目列表
echo ""
echo "[4/5] 测试查询项目列表..."
RESPONSE=$(curl -s -X GET "$BASE_URL/ccdi/project/list?pageNum=1&pageSize=5" \
  -H "Authorization: Bearer $TOKEN")

if echo "$RESPONSE" | grep -q '"code":200'; then
  echo "✓ 查询项目列表成功"

  if echo "$RESPONSE" | grep -q '"lsfxProjectId"'; then
    echo "✓ 列表包含lsfxProjectId字段"
  else
    echo "! 列表可能缺少lsfxProjectId字段"
  fi
else
  echo "✗ 查询失败"
fi

# 5. 测试查询项目详情
echo ""
echo "[5/5] 测试查询项目详情..."
PROJECT_ID=$(curl -s -X GET "$BASE_URL/ccdi/project/list?pageNum=1&pageSize=1" \
  -H "Authorization: Bearer $TOKEN" | grep -o '"projectId":[0-9]*' | head -1 | sed 's/"projectId"://')

if [ -n "$PROJECT_ID" ]; then
  RESPONSE=$(curl -s -X GET "$BASE_URL/ccdi/project/$PROJECT_ID" \
    -H "Authorization: Bearer $TOKEN")

  if echo "$RESPONSE" | grep -q '"lsfxProjectId"'; then
    echo "✓ 项目详情包含lsfxProjectId"
  else
    echo "! 项目详情缺少lsfxProjectId"
  fi
else
  echo "! 没有找到项目"
fi

echo ""
echo "=========================================="
echo "测试完成！"
echo "=========================================="
