#!/bin/bash

# 执行E2E测试脚本
# 作者: 张翔
# 日期: 2026-04-15

set -e

echo "=========================================="
echo "执行用户旅程测试 (E2E)"
echo "=========================================="

# 检查Node.js是否安装
if ! command -v node &> /dev/null; then
    echo "错误: Node.js 未安装"
    exit 1
fi

# 检查包管理器
if command -v pnpm &> /dev/null; then
    PACKAGE_MANAGER="pnpm"
elif command -v npm &> /dev/null; then
    PACKAGE_MANAGER="npm"
else
    echo "错误: 未找到包管理器"
    exit 1
fi

# 进入前端项目目录
cd "$(dirname "$0")/../novalon-manage-web"

echo "1. 检查测试环境..."
echo "   测试类型: 冒烟测试 (登录登出流程)"
echo "   测试文件: e2e/smoke/login-logout.spec.ts"
echo "   测试数据:"
echo "     - 管理员账号: admin/Test@123"
echo "     - 普通用户账号: user/Test@123"
echo ""

echo "2. 验证后端服务..."
if ! curl -s http://localhost:8084/actuator/health > /dev/null; then
    echo "警告: 后端服务未运行，测试可能失败"
    echo "请确保后端服务已启动 (http://localhost:8084)"
    read -p "是否继续? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
else
    echo "✅ 后端服务运行正常"
fi

echo "3. 验证前端服务..."
if ! curl -s http://localhost:3000 > /dev/null; then
    echo "警告: 前端服务未运行，测试可能失败"
    echo "请确保前端服务已启动 (http://localhost:3000)"
    read -p "是否继续? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
else
    echo "✅ 前端服务运行正常"
fi

echo "4. 执行冒烟测试..."
echo "   测试将在浏览器中运行，请勿操作浏览器"
echo "   测试结果将显示在控制台并生成报告"
echo ""

# 执行冒烟测试
$PACKAGE_MANAGER run test:e2e:smoke

echo ""
echo "=========================================="
echo "测试完成！"
echo "=========================================="
echo ""
echo "测试报告位置:"
echo "   - HTML报告: novalon-manage-web/playwright-report/"
echo "   - 测试截图: novalon-manage-web/test-results/"
echo ""
echo "其他测试命令:"
echo "   - 所有E2E测试: $PACKAGE_MANAGER run test:e2e"
echo "   - 核心旅程测试: $PACKAGE_MANAGER run test:e2e:journeys"
echo "   - 调试模式: $PACKAGE_MANAGER run test:e2e:debug"
echo "   - 带界面运行: $PACKAGE_MANAGER run test:e2e:headed"