/**
 * 关键旅程 E2E 测试 05: 发布→首页可见
 * Journey: 创建内容 → 发布内容 → 验证在首页可见
 */
import { test, expect } from '@playwright/test';
import { apiGet, apiPost, apiPut, initApiClient, disposeApiClient, setAuthToken } from '../../../helpers/api-client';

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

test.describe('关键旅程 05: 发布内容', () => {
  let phone: string;
  let authToken: string;
  let testBookId: number;

  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('C05-1: 创建测试书籍用于发布', async () => {
    const res = await apiPost('/api/book-generator/langgraph/create', {
      title: `发布测试书籍_${Date.now()}`,
      topic: '测试主题',
      wordCount: 10000,
    });
    expect(res.code).toBe(0);
    testBookId = res.data?.bookId;
    expect(testBookId).toBeDefined();
  });

  test('C05-2: 获取发布状态', async () => {
    if (!testBookId) return test.skip();
    const res = await apiGet(`/api/book-generator/langgraph/books/${testBookId}`);
    // 刚创建的书籍应该是 draft 状态
    expect(res.code).toBe(0);
  });

  test('C05-3: 发布书籍', async () => {
    if (!testBookId) return test.skip();
    const res = await apiPut(`/api/book-generator/langgraph/books/${testBookId}/publish`);
    expect([0, 400, 409]).toContain(res.code); // 0=成功，其他=业务错误
  });

  test('C05-4: 发布页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/publish/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('#app')).toBeVisible();
  });

  test('C05-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('C05-6: 获取书籍列表验证已发布', async () => {
    const res = await apiGet('/api/book-generator/langgraph/books');
    expect(res.code).toBe(0);
    // 列表中应该包含我们创建的书籍
    const books = res.data?.books || [];
    const found = books.some((b: any) => b.id === testBookId);
    expect(found).toBe(true);
  });

  test('C05-7: 播放列表页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/playlists/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('#app')).toBeVisible();
  });
});