import { describe, expect, it } from 'vitest';

import { buildSearchDisplayErrors, summarizeSearchProgressMessage } from '@/components/shared/searchProgressDialogUtils';

describe('searchProgressDialogUtils', () => {
  it('strips stdout and stderr details from backend error messages', () => {
    const rawMessage = [
      '物料 182cf498-538e-4697-9b84-1eba053f062e 失败: 物料搜索执行失败: exit 1',
      '[stdout]',
      '[sync] 开始处理...',
      '[stderr]',
      'Error: stack trace',
    ].join('\n');

    expect(summarizeSearchProgressMessage(rawMessage)).toBe(
      '物料 182cf498-538e-4697-9b84-1eba053f062e 失败: 物料搜索执行失败: exit 1',
    );
  });

  it('deduplicates summarized errors from progress and result', () => {
    const detailedError = [
      '搜索执行失败: exit 1',
      '[stdout]',
      'line 1',
    ].join('\n');

    expect(buildSearchDisplayErrors([detailedError, ''], detailedError)).toEqual([
      '搜索执行失败: exit 1',
    ]);
  });

  it('prefers nested business errors over generic exit 1 messages', () => {
    const rawMessage = [
      '物料 dca98140 搜索 执行失败: exit 1',
      '[stdout]',
      '首轮 1688 文字搜索 执行失败: exit 1',
      '[stderr]',
      'Error: 有头模式人工验证未完成：当前页面仍需要验证码或二次验证',
    ].join('\n');

    expect(summarizeSearchProgressMessage(rawMessage)).toBe(
      '有头模式人工验证未完成：当前页面仍需要验证码或二次验证',
    );
  });

  it('turns nested Playwright runtime errors into readable task errors', () => {
    expect(summarizeSearchProgressMessage([
      '搜索执行失败: exit 1',
      '[stderr]',
      'page.goto: Timeout 20000ms exceeded.',
    ].join('\n'))).toBe('页面操作超时：page.goto 超过 20000ms');

    expect(summarizeSearchProgressMessage([
      '搜索执行失败: exit 1',
      '[stderr]',
      'browserType.launchPersistentContext: Target page, context or browser has been closed',
    ].join('\n'))).toBe('浏览器页面已关闭，可能是人工验证窗口被关闭');
  });

  it('translates English reason-code summaries before display', () => {
    expect(summarizeSearchProgressMessage('browser_target_crashed')).toBe('搜索浏览器崩溃，未进入结果页');
    expect(summarizeSearchProgressMessage('future_internal_reason_code')).toBe('系统已记录失败原因，请稍后重试或查看任务日志');
  });
});
