/**
 * 关键旅程 E2E 测试 03: 书籍生成完整流水线
 * 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('关键旅程 03: 书籍生成流水线', () => {
  let phone: string;
  let authToken: string;
  let bookId: 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('C03-1: 预估字数和时长', async () => {
    const res = await apiPost('/api/book-generator/langgraph/estimate', {
      topic: '人工智能发展史',
      wordCount: 50000,
    });
    expect(res.code).toBe(0);
    expect(res.data?.estimatedCost).toBeGreaterThan(0);
    expect(res.data?.estimatedDuration).toBeGreaterThan(0);
  });

  test('C03-2: 检测书籍类型', async () => {
    const res = await apiPost('/api/book-generator/langgraph/detect-book-type', {
      topic: '人工智能简史',
    });
    expect(res.code).toBe(0);
    expect(['技术', '科普', '学术', '其他']).toContain(res.data?.bookType);
  });

  test('C03-3: 创建书籍', async () => {
    const res = await apiPost('/api/book-generator/langgraph/create', {
      title: `自动化测试书籍_${Date.now()}`,
      topic: '人工智能发展史',
      wordCount: 30000,
      strategy: 'deep-plan-parallel',
    });
    expect(res.code).toBe(0);
    bookId = res.data?.bookId;
    expect(bookId).toBeDefined();
  });

  test('C03-4: 获取书籍详情', async () => {
    if (!bookId) return test.skip();
    const res = await apiGet(`/api/book-generator/langgraph/books/${bookId}`);
    expect(res.code).toBe(0);
    expect(res.data?.id).toBe(bookId);
  });

  test('C03-5: 获取章节列表', async () => {
    if (!bookId) return test.skip();
    const res = await apiGet(`/api/book-generator/langgraph/books/${bookId}/chapters`);
    expect(res.code).toBe(0);
  });

  test('C03-6: 获取用户书籍列表', async () => {
    const res = await apiGet('/api/book-generator/langgraph/books');
    expect(res.code).toBe(0);
    expect(Array.isArray(res.data?.books)).toBe(true);
  });

  test('C03-7: 书籍生成列表页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/book-generator/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('text=书籍生成').first()).toBeVisible();
  });

  test('C03-8: 书籍创建页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/book-generator/create`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('text=创建书籍').first()).toBeVisible();
  });
});