/**
 * 关键旅程 E2E 测试 01: 注册→登录→首页浏览
 * Journey: 新用户注册 → 获取Token → 浏览首页
 */
import { test, expect } from '@playwright/test';
import { apiGet, apiPost, apiDelete, initApiClient, disposeApiClient, setAuthToken } from '../../../helpers/api-client';

const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:5173';

test.describe('关键旅程 01: 注册登录', () => {
  let phone: string;
  let authToken: string;

  test.beforeAll(async () => {
    await initApiClient();
    phone = `138${String(Date.now()).slice(-8)}`;
  });

  test.afterAll(async () => {
    await disposeApiClient();
  });

  test('C01-1: 发送验证码', async () => {
    const res = await apiPost('/api/auth/send-code', { phone });
    expect(res.code).toBe(0);
    expect(res.data?.code).toBeDefined();
  });

  test('C01-2: 验证码登录/注册', async () => {
    const res = await apiPost('/api/auth/login', {
      phone,
      code: '123456', // 测试验证码
    });
    expect(res.code).toBe(0);
    expect(res.data?.token).toBeDefined();

    authToken = res.data?.token;
    setAuthToken(authToken);
  });

  test('C01-3: 获取用户信息', async () => {
    const res = await apiGet('/api/auth/user-info');
    expect(res.code).toBe(0);
    expect(res.data?.phone).toBe(phone);
  });

  test('C01-4: 新用户默认免费会员(memberLevel=0)', async () => {
    const res = await apiGet('/api/auth/user-info');
    expect(res.data?.memberLevel).toBe(0);
  });

  test('C01-5: 首页可正常访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/index/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('#app')).toBeVisible();
  });

  test('C01-6: 清理测试用户', async () => {
    // 如果后端支持删除账户则调用，否则跳过
    try {
      await apiDelete('/api/auth/account');
    } catch {
      // 跳过清理
    }
  });
});