#!/bin/bash

# 在 WSL2 中运行完整测试（使用 Docker 提供的测试数据库）

set -e

BLUE='\033[0;34m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

echo -e "${BLUE}=== Admin Service Complete Test Suite ===${NC}"

# 1. 启动 PostgreSQL 测试数据库容器
echo -e "${YELLOW}1. Starting PostgreSQL test database...${NC}"
docker run -d \
  --name admin-test-db \
  --rm \
  -e POSTGRES_USER=postgres \
  -e POSTGRES_PASSWORD=password \
  -e POSTGRES_DB=admin_service_test \
  -p 5433:5432 \
  postgres:16-alpine

echo -e "${YELLOW}Waiting for database to be ready...${NC}"
sleep 5

# 2. 检查数据库连接
echo -e "${YELLOW}2. Checking database connection...${NC}"
until docker exec admin-test-db pg_isready -U postgres; do
  echo "Waiting for database..."
  sleep 2
done
echo -e "${GREEN}✓ Database is ready${NC}"

# 3. 设置环境变量
export DATABASE_URL="postgresql://postgres:password@localhost:5433/admin_service_test?schema=public"
export NODE_ENV=test

# 4. 安装依赖（如果需要）
if [ ! -d "node_modules" ]; then
  echo -e "${YELLOW}3. Installing dependencies...${NC}"
  npm ci
fi

# 5. 生成 Prisma 客户端
echo -e "${YELLOW}4. Generating Prisma client...${NC}"
npm run prisma:generate

# 6. 运行数据库迁移
echo -e "${YELLOW}5. Running database migrations...${NC}"
npx prisma migrate deploy

# 7. 运行单元测试
echo -e "${BLUE}=== Running Unit Tests ===${NC}"
npm run test:unit

# 8. 运行集成测试
echo -e "${BLUE}=== Running Integration Tests ===${NC}"
npm run test:integration

# 9. 运行 E2E 测试
echo -e "${BLUE}=== Running E2E Tests ===${NC}"
npm run test:e2e

# 10. 生成覆盖率报告
echo -e "${BLUE}=== Generating Coverage Report ===${NC}"
npm run test:cov

echo -e "${GREEN}=== All tests completed successfully! ===${NC}"

# 11. 清理
echo -e "${YELLOW}Cleaning up test database...${NC}"
docker stop admin-test-db

echo -e "${GREEN}✓ Test suite finished${NC}"
echo -e "${BLUE}Coverage report: ./coverage/lcov-report/index.html${NC}"
