#!/bin/bash

echo "=================================================="
echo "🧪 学校端排课功能 - 完整API测试"
echo "=================================================="

BASE_URL="http://localhost:8080"

# 1. 登录获取token
echo ""
echo "1️⃣ 登录测试..."
LOGIN_RESPONSE=$(curl -s -X POST $BASE_URL/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"username":"school1","password":"123456"}')

TOKEN=$(echo $LOGIN_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(d['data']['token'])" 2>/dev/null)
USER_ROLE=$(echo $LOGIN_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(d['data']['role'])" 2>/dev/null)

if [ -z "$TOKEN" ]; then
  echo "   ❌ 登录失败"
  exit 1
fi

echo "   ✅ 登录成功"
echo "   📝 Token: ${TOKEN:0:50}..."
echo "   👤 角色: $USER_ROLE"

# 2. 测试课程套餐列表（两层结构）
echo ""
echo "2️⃣ 测试课程套餐列表（两层结构）..."
PACKAGES_RESPONSE=$(curl -s $BASE_URL/api/v1/school/packages \
  -H "Authorization: Bearer $TOKEN")

PACKAGE_COUNT=$(echo $PACKAGES_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(len(d.get('data', [])))" 2>/dev/null)
echo "   ✅ 返回 $PACKAGE_COUNT 个课程套餐"

# 显示第一个套餐的结构
if [ "$PACKAGE_COUNT" -gt 0 ]; then
  echo ""
  echo "   📦 课程套餐结构示例:"
  echo $PACKAGES_RESPONSE | python3 -c "
import sys, json
d = json.load(sys.stdin)
if d.get('data') and len(d['data']) > 0:
    pkg = d['data'][0]
    print(f'      ID: {pkg.get(\"id\")}')
    print(f'      名称: {pkg.get(\"name\")}')
    print(f'      课程包数量: {pkg.get(\"packageCount\")}')
    if pkg.get('packages'):
        print(f'      包含课程包:')
        for p in pkg['packages']:
            print(f'         - {p.get(\"name\")} (包含 {p.get(\"courseCount\")} 门课程)')
"
fi

# 3. 测试排课列表
echo ""
echo "3️⃣ 测试排课列表..."
SCHEDULES_RESPONSE=$(curl -s "$BASE_URL/api/v1/school/schedules?pageNum=1&pageSize=10" \
  -H "Authorization: Bearer $TOKEN")

SCHEDULE_TOTAL=$(echo $SCHEDULES_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('data', {}).get('total', 0))" 2>/dev/null)
echo "   ✅ 排课记录总数: $SCHEDULE_TOTAL"

if [ "$SCHEDULE_TOTAL" -gt 0 ]; then
  echo ""
  echo "   📋 排课记录示例:"
  echo $SCHEDULES_RESPONSE | python3 -c "
import sys, json
d = json.load(sys.stdin)
if d.get('data') and d['data'].get('list'):
    item = d['data']['list'][0]
    print(f'      ID: {item.get(\"id\")}')
    print(f'      名称: {item.get(\"name\")}')
    print(f'      班级: {item.get(\"className\")}')
    print(f'      教师: {item.get(\"teacherName\")}')
"
fi

# 4. 测试课表视图API
echo ""
echo "4️⃣ 测试课表视图API..."
START_DATE=$(date +%Y-%m-%d)
END_DATE=$(date -v+7d +%Y-%m-%d 2>/dev/null || date -d '+7 days' +%Y-%m-%d 2>/dev/null)

TIMETABLE_RESPONSE=$(curl -s "$BASE_URL/api/v1/school/schedules/timetable?startDate=$START_DATE&endDate=$END_DATE" \
  -H "Authorization: Bearer $TOKEN")

TIMETABLE_COUNT=$(echo $TIMETABLE_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(len(d.get('data', [])))" 2>/dev/null)
echo "   ✅ 课表数据返回: $TIMETABLE_COUNT 条记录"

# 5. 测试班级列表
echo ""
echo "5️⃣ 测试班级列表..."
CLASSES_RESPONSE=$(curl -s $BASE_URL/api/v1/school/classes \
  -H "Authorization: Bearer $TOKEN")

CLASS_COUNT=$(echo $CLASSES_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(len(d.get('data', [])))" 2>/dev/null)
echo "   ✅ 班级总数: $CLASS_COUNT"

# 6. 测试教师列表
echo ""
echo "6️⃣ 测试教师列表..."
TEACHERS_RESPONSE=$(curl -s "$BASE_URL/api/v1/school/teachers?pageNum=1&pageSize=50" \
  -H "Authorization: Bearer $TOKEN")

TEACHER_COUNT=$(echo $TEACHERS_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('data', {}).get('total', 0))" 2>/dev/null)
echo "   ✅ 教师总数: $TEACHER_COUNT"

# 7. 测试冲突检测API
echo ""
echo "7️⃣ 测试冲突检测API..."
CONFLICT_RESPONSE=$(curl -s -X POST "$BASE_URL/api/v1/school/schedules/check-conflict" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "classId=1&teacherId=1&scheduledDate=2026-03-20&scheduledTime=09:00-10:00")

CONFLICT_CODE=$(echo $CONFLICT_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin); print(d.get('code', 'ERROR'))" 2>/dev/null)
CONFLICT_HAS=$(echo $CONFLICT_RESPONSE | python3 -c "import sys, json; d=json.load(sys.stdin)['data'].get('hasConflict', 'N/A')" 2>/dev/null)
if [ "$CONFLICT_CODE" = "200" ]; then
  echo "   ✅ 冲突检测API正常 (hasConflict=$CONFLICT_HAS)"
else
  echo "   ⚠️  冲突检测API响应码: $CONFLICT_CODE"
fi

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