/**
 * 关键旅程 E2E 测试 02: TTS生成→播放
 * Journey: 登录 → 输入文本 → 选择音色 → 生成音频 → 播放
 */
import { test, expect } from '@playwright/test';
import { apiGet, apiPost, initApiClient, disposeApiClient, setAuthToken } from '../../../helpers/api-client';

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

test.describe('关键旅程 02: TTS生成播放', () => {
  let phone: string;
  let authToken: string;
  let audioId: string;

  test.beforeAll(async () => {
    await initApiClient();
    // 创建测试用户
    phone = `138${String(Date.now()).slice(-8)}`;
    await apiPost('/api/auth/send-code', { phone });
    const loginRes = await apiPost('/api/auth/login', { phone, code: '123456' });
    authToken = loginRes.data?.token;
    setAuthToken(authToken);
  });

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

  test('C02-1: 获取音色列表', async () => {
    const res = await apiGet('/api/tts/voices');
    expect(res.code).toBe(0);
    expect(res.data?.voices).toBeDefined();
    expect(Array.isArray(res.data.voices)).toBe(true);
    expect(res.data.voices.length).toBeGreaterThan(0);
  });

  test('C02-2: 获取提供商列表', async () => {
    const res = await apiGet('/api/tts/providers');
    expect(res.code).toBe(0);
  });

  test('C02-3: 生成TTS音频任务', async () => {
    const res = await apiPost('/api/tts/generate', {
      text: '这是一段自动化测试文本，用于验证TTS音频生成功能。人工智能正在改变我们的生活方式。',
      voiceId: 'Cherry',
      voiceParams: { speed: 1.0, pitch: 0, volume: 50 },
    });
    expect(res.code).toBe(0);
    audioId = res.data?.audioId;
    expect(audioId).toBeDefined();
  });

  test('C02-4: 查询音频生成状态', async () => {
    if (!audioId) return test.skip();
    // 状态接口可能需要等待，实际应该轮询
    const res = await apiGet(`/api/tts/status/${audioId}`);
    expect([0, 1, 2, 404]).toContain(res.code); // 0=成功, 1=处理中, 2=失败
  });

  test('C02-5: TTS生成页可正常访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/create/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('text=生成音频').first()).toBeVisible();
  });

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