import { test, expect } from '@playwright/test';

test.describe('API连通性测试', () => {
  test('验证网关服务健康状态', async ({ page }) => {
    await test.step('检查网关健康状态', async () => {
      const response = await page.request.get('http://localhost:8080/actuator/health');
      expect(response.status()).toBe(200);
      
      const data = await response.json();
      expect(data.status).toBe('UP');
    });

    await test.step('检查应用服务路由', async () => {
      const response = await page.request.get('http://localhost:8080/api/auth/health');
      expect(response.status()).toBe(200);
    });
  });

  test('验证前端与后端连通性', async ({ page }) => {
    await test.step('加载前端应用', async () => {
      await page.goto('/');
      await page.waitForLoadState('networkidle');
      
      // 验证页面标题
      const title = await page.title();
      expect(title).toContain('Novalon');
    });

    await test.step('检查API请求', async () => {
      // 监听网络请求
      const apiRequests = [];
      page.on('request', request => {
        if (request.url().includes('/api/')) {
          apiRequests.push({
            url: request.url(),
            method: request.method()
          });
        }
      });

      // 触发一些前端操作来生成API请求
      await page.goto('/login');
      await page.waitForLoadState('networkidle');
      
      // 验证是否有API请求发出
      expect(apiRequests.length).toBeGreaterThan(0);
    });
  });

  test('验证数据库连接状态', async ({ page }) => {
    await test.step('检查数据库健康状态', async () => {
      // 通过应用服务检查数据库连接
      const response = await page.request.get('http://localhost:8084/actuator/health');
      expect(response.status()).toBe(200);
      
      const data = await response.json();
      expect(data.status).toBe('UP');
      
      // 检查数据库组件状态
      if (data.components && data.components.db) {
        expect(data.components.db.status).toBe('UP');
      }
    });
  });
});