/**
 * L2 回归测试：认证模块
 * 覆盖：发送验证码、登录、获取用户信息、更新用户信息
 */
import { test, expect } from '@playwright/test';
import { apiGet, apiPost, apiPut, initApiClient, disposeApiClient, setAuthToken } from '../helpers/api-client';

let token: string;
let phone: string;

test.describe('认证模块 (Auth)', () => {
  test.beforeAll(async () => {
    await initApiClient();
    phone = `138${String(Date.now()).slice(-8)}`;
  });

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

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

  test('A02: 手机号登录 POST /api/auth/login', async () => {
    const codeRes = await apiPost('/api/auth/send-code', { phone });
    const code = codeRes.data?.code || '123456';

    const res = await apiPost('/api/auth/login', { phone, code });
    expect(res.code).toBe(0);
    expect(res.data?.token).toBeDefined();
    token = res.data.token;
    setAuthToken(token);
  });

  test('A03: 获取用户信息 GET /api/auth/user-info', async () => {
    const res = await apiGet('/api/auth/user-info');
    // 需要 token，可能 401 如果没有中间件豁免
    expect([0, 401]).toContain(res.code);
  });

  test('A04: 无效手机号被拒绝', async () => {
    const res = await apiPost('/api/auth/send-code', { phone: '12345' });
    expect(res.code).not.toBe(0);
  });
});
