/**
 * 调试课程创建 - 检查 500 错误详情
 */
import { test, expect } from '@playwright/test';
import { loginAsAdmin } from './helpers';

test.describe('课程创建调试 - 500 错误详情', () => {
  test('获取 500 错误详情', async ({ page, request }) => {
    test.setTimeout(180000);

    const courseName = '调试测试课程包-' + Date.now();
    console.log('=== 测试开始 ===');

    // 步骤 1: 登录并获取 token
    console.log('=== 步骤 1: 登录 ===');
    await loginAsAdmin(page);
    await page.waitForTimeout(2000);

    // 从 localStorage 获取 token
    const token = await page.evaluate(() => localStorage.getItem('token'));
    console.log('Token:', token ? `${token.substring(0, 20)}...` : 'null');

    // 步骤 2: 进入课程创建页面并填写表单
    console.log('=== 步骤 2: 填写表单 ===');
    await page.goto('/admin/courses/create', { timeout: 30000, waitUntil: 'networkidle' });
    await page.waitForTimeout(3000);

    await page.getByPlaceholder('请输入课程包名称').fill(courseName);
    await page.locator('.ant-select-selector').first().click();
    await page.waitForTimeout(500);
    await page.getByText('社会认知', { exact: true }).first().click();
    await page.waitForTimeout(300);
    await page.getByRole('checkbox', { name: '小班' }).check();
    await page.waitForTimeout(300);
    await page.getByPlaceholder('请输入课程包核心内容').fill('调试测试课程内容');

    // 步骤 3: 点击下一步到最后
    console.log('=== 步骤 3: 点击下一步 ===');
    for (let i = 0; i < 6; i++) {
      const nextButton = page.getByRole('button', { name: '下一步' });
      if (await nextButton.isVisible().catch(() => false)) {
        await nextButton.click();
        await page.waitForTimeout(800);
      }
    }
    await page.waitForTimeout(1000);

    // 步骤 4: 点击创建按钮并捕获错误响应
    console.log('=== 步骤 4: 点击创建并捕获错误 ===');

    const submitButton = page.locator('.step-actions .ant-btn-primary').last();
    await submitButton.click();
    console.log('已点击提交按钮');

    // 等待 API 响应
    const response = await page.waitForResponse(
      res => res.url().includes('/api/v1/admin/courses') && res.request().method() === 'POST',
      { timeout: 15000 }
    ).catch(() => null);

    if (response) {
      console.log('响应状态:', response.status());
      const responseBody = await response.text();
      console.log('响应体:', responseBody);

      try {
        const json = JSON.parse(responseBody);
        console.log('JSON 响应:', JSON.stringify(json, null, 2));
      } catch {
        console.log('无法解析 JSON');
      }
    } else {
      console.log('未捕获到 API 响应');
    }

    // 等待更长时间查看错误消息
    await page.waitForTimeout(5000);

    // 检查是否有错误消息
    const errorMsg = await page.locator('.ant-message-error').first();
    const errorMsgVisible = await errorMsg.isVisible().catch(() => false);
    if (errorMsgVisible) {
      const errorText = await errorMsg.textContent();
      console.log('错误消息:', errorText);
    } else {
      console.log('没有显示错误消息');
    }

    // 截图
    await page.screenshot({ path: 'test-results/debug-500-error.png' });
  });
});
