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

import { resolveDocumentTaskErrorText } from './document-import-error';

const translate = (key: string) => `translated:${key}`;

describe('resolveDocumentTaskErrorText', () => {
  it('uses the stable backend error code', () => {
    expect(
      resolveDocumentTaskErrorText(
        { lastTaskErrorCode: 'parse_service_unavailable' },
        translate,
      ),
    ).toBe('translated:documentCollection.importDoc.parseServiceUnavailable');
  });

  it('supports the error code stored in document options', () => {
    expect(
      resolveDocumentTaskErrorText(
        { options: { 'task.errorCode': 'pending_timeout' } },
        translate,
      ),
    ).toBe('translated:documentCollection.importDoc.taskPendingTimeout');
  });

  it('normalizes legacy MinerU 503 errors', () => {
    expect(
      resolveDocumentTaskErrorText(
        {
          lastTaskError:
            'MinerU request failed: path=/tasks, status=503, body=',
        },
        translate,
      ),
    ).toBe('translated:documentCollection.importDoc.parseServiceUnavailable');
  });

  it('distinguishes legacy internal document access errors from MinerU errors', () => {
    expect(
      resolveDocumentTaskErrorText(
        {
          lastTaskError:
            '下载文档 URL 失败: http://127.0.0.1/file.docx; 远端文档地址不允许访问非公网目标',
        },
        translate,
      ),
    ).toBe('translated:documentCollection.importDoc.documentSourceUnavailable');
  });

  it('uses the stable document source error code', () => {
    expect(
      resolveDocumentTaskErrorText(
        { lastTaskErrorCode: 'document_source_unavailable' },
        translate,
      ),
    ).toBe('translated:documentCollection.importDoc.documentSourceUnavailable');
  });

  it('keeps unknown business errors intact', () => {
    expect(
      resolveDocumentTaskErrorText(
        { lastTaskError: '文档内容为空' },
        translate,
      ),
    ).toBe('文档内容为空');
  });
});
