/**
 * 关键旅程 E2E 测试 04: 购买会员→解锁功能
 * 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('关键旅程 04: 订阅会员解锁功能', () => {
  let phone: string;
  let authToken: string;
  let orderNo: 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('C04-1: 获取可用套餐列表', async () => {
    const res = await apiGet('/api/payment/plans');
    expect(res.code).toBe(0);
    expect(Array.isArray(res.data?.plans)).toBe(true);
    expect(res.data?.plans.length).toBeGreaterThan(0);
  });

  test('C04-2: 获取单个套餐详情', async () => {
    const res = await apiGet('/api/payment/plan/2');
    expect(res.code).toBe(0);
    expect(res.data?.name).toBeDefined();
  });

  test('C04-3: 创建支付订单', async () => {
    const res = await apiPost('/api/payment/create-order', {
      planId: 2, // 专业版
      paymentMethod: 'mock',
      period: 'monthly',
    });
    expect(res.code).toBe(0);
    expect(res.data?.orderNo).toBeDefined();
    orderNo = res.data?.orderNo;
  });

  test('C04-4: 模拟支付成功回调', async () => {
    if (!orderNo) return test.skip();
    const callbackRes = await apiPost('/api/payment/callback/mock', {
      orderNo,
      paymentId: `MOCK_${Date.now()}`,
      status: 'success',
    });
    expect(callbackRes.code).toBe(0);
  });

  test('C04-5: 会员等级已更新', async () => {
    const res = await apiGet('/api/auth/user-info');
    expect(res.code).toBe(0);
    // 支付后会员等级应该 >= 1 (专业版)
    expect(res.data?.memberLevel).toBeGreaterThanOrEqual(1);
  });

  test('C04-6: 会员中心页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/member/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('#app')).toBeVisible();
  });

  test('C04-7: 订单页可访问', async ({ page }) => {
    await page.goto(`${FRONTEND_URL}/#/pages/orders/index`, { waitUntil: 'networkidle', timeout: 30000 });
    await page.waitForTimeout(3000);
    await expect(page.locator('#app')).toBeVisible();
  });

  test('C04-8: 查询订单列表', async () => {
    const res = await apiGet('/api/payment/orders');
    expect(res.code).toBe(0);
    expect(Array.isArray(res.data?.list)).toBe(true);
  });
});