import { test as base } from '@playwright/test';

/**
 * 认证 Fixture
 * 提供通用的登录功能和 API 请求封装
 */

type AuthFixture = {
  // UI 登录
  loginViaUI: (tenantCode: string, username?: string, password?: string) => Promise<void>;
  // API 登录
  loginViaAPI: (tenantCode: string, username?: string, password?: string) => Promise<{
    token: string;
    userId: number;
    tenantCode: string;
  }>;
  // 获取带认证的请求头
  getAuthHeaders: (token: string) => Record<string, string>;
};

export const test = base.extend<AuthFixture>({
  // UI 登录实现
  loginViaUI: async ({ page }, use) => {
    const loginFn = async (tenantCode: string, username = 'admin', password = 'admin123') => {
      // 访问登录页
      await page.goto(`/${tenantCode}/login`);
      await page.waitForLoadState('networkidle');

      // 填写表单
      await page.fill('input[placeholder="请输入用户名"]', username);
      await page.fill('input[placeholder="请输入密码"]', password);

      // 点击登录按钮
      await page.click('button[type="submit"]');

      // 等待网络请求完成
      await page.waitForLoadState('networkidle');

      // 等待 URL 变化（不再是登录页）
      await page.waitForFunction(
        () => !window.location.pathname.includes('/login'),
        { timeout: 10000 }
      );

      // 等待页面稳定
      await page.waitForTimeout(2000);

      // 验证已成功登录
      const currentUrl = page.url();
      if (currentUrl.includes('/login')) {
        throw new Error(`登录失败，停留在登录页：${currentUrl}`);
      }

      console.log(`✓ UI 登录成功 [${tenantCode}]，当前 URL:`, currentUrl);
    };

    await use(loginFn);
  },

  // API 登录实现
  loginViaAPI: async ({ request }, use) => {
    const loginFn = async (tenantCode: string, username = 'admin', password = 'admin123') => {
      const API_BASE = 'http://localhost:8580';

      const response = await request.post(`${API_BASE}/api/auth/login`, {
        data: {
          username,
          password,
          tenantCode,
        },
      });

      const data = await response.json();

      if (data.code !== 200 || !data.data?.token) {
        throw new Error(`API 登录失败：${data.message || '未知错误'}`);
      }

      console.log(`✓ API 登录成功 [${tenantCode}]`);

      return {
        token: data.data.token,
        userId: data.data.user?.id,
        tenantCode: data.data.user?.tenantCode,
      };
    };

    await use(loginFn);
  },

  // 获取带认证的请求头
  getAuthHeaders: async ({}, use) => {
    const getHeaders = (token: string) => ({
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    });

    await use(getHeaders);
  },
});

export { expect } from '@playwright/test';
