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

test.describe('认证和授权测试', () => {
  let authToken: string;
  let userId: number;

  test.beforeAll(async ({ request }) => {
    const response = await request.post('http://localhost:8080/api/auth/login', {
      headers: {
        'Content-Type': 'application/json'
      },
      data: {
        username: 'admin',
        password: 'Test@123'
      }
    });

    expect(response.status()).toBe(200);
    const data = await response.json();
    authToken = data.token;
    userId = data.userId;
    console.log('认证测试初始化完成，Token:', authToken.substring(0, 20) + '...');
  });

  test('用户登录测试', async ({ page }) => {
    await test.step('准备登录数据', async () => {
      console.log('准备登录测试数据...');
    });

    await test.step('发送登录请求', async () => {
      const response = await page.request.post('http://localhost:8080/api/auth/login', {
        headers: {
          'Content-Type': 'application/json'
        },
        data: {
          username: 'admin',
          password: 'Test@123'
        }
      });

      expect(response.status()).toBe(200);
      
      const data = await response.json();
      expect(data).toHaveProperty('token');
      expect(data).toHaveProperty('userId');
      expect(data).toHaveProperty('username');
      
      console.log('登录成功，获取到Token:', data.token.substring(0, 20) + '...');
    });

    await test.step('验证Token有效性', async () => {
      const response = await page.request.get('http://localhost:8080/api/users', {
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });

      expect(response.status()).toBe(200);
      console.log('Token验证成功，可以访问受保护的资源');
    });
  });

  test('用户信息查询测试', async ({ page }) => {
    await test.step('查询用户列表', async () => {
      const response = await page.request.get('http://localhost:8080/api/users', {
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });

      expect(response.status()).toBe(200);
      
      const users = await response.json();
      expect(Array.isArray(users)).toBe(true);
      expect(users.length).toBeGreaterThan(0);
      
      console.log(`查询到 ${users.length} 个用户`);
    });

    await test.step('查询指定用户信息', async () => {
      const response = await page.request.get(`http://localhost:8080/api/users/${userId}`, {
        headers: {
          'Authorization': `Bearer ${authToken}`
        }
      });

      expect(response.status()).toBe(200);
      
      const user = await response.json();
      expect(user).toHaveProperty('id');
      expect(user).toHaveProperty('username');
      expect(user.id).toBe(userId);
      
      console.log(`查询到用户信息: ${user.username}`);
    });
  });

  test('权限验证测试', async ({ page }) => {
    await test.step('测试访问受保护的API', async () => {
      const protectedEndpoints = [
        '/api/users',
        '/api/roles',
        '/api/menus',
        '/api/config'
      ];

      for (const endpoint of protectedEndpoints) {
        const response = await page.request.get(`http://localhost:8080${endpoint}`, {
          headers: {
            'Authorization': `Bearer ${authToken}`
          }
        });

        console.log(`访问 ${endpoint}: ${response.status()}`);
        expect([200, 404]).toContain(response.status());
      }
    });

    await test.step('测试无Token访问受保护API', async () => {
      const response = await page.request.get('http://localhost:8080/api/users');
      
      expect(response.status()).toBe(401);
      console.log('无Token访问受保护API返回401，权限验证正常');
    });
  });

  test('前端登录流程测试', async ({ page }) => {
    await test.step('验证已登录状态', async () => {
      await page.goto('/dashboard');
      await page.waitForLoadState('networkidle');
      await page.waitForTimeout(3000);
      
      await expect(page).toHaveURL(/.*dashboard/);
      
      const userButton = page.getByRole('button', { name: 'admin' });
      await expect(userButton).toBeVisible({ timeout: 15000 });
      
      console.log('已登录状态验证通过');
    });

    await test.step('验证可以访问受保护页面', async () => {
      await page.goto('/users');
      await page.waitForLoadState('networkidle');
      
      await expect(page).toHaveURL(/.*users/);
      
      console.log('受保护页面访问验证通过');
    });
  });
});