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

import { resolveDocumentUploadResponse } from './document-import-upload-response';

const fallbackMessage = '文件上传失败';

describe('resolveDocumentUploadResponse', () => {
  it.each([
    ['数字错误码', '{"errorCode":0}'],
    ['字符串错误码', '{"errorCode":"0"}'],
    ['兼容 code 字段', '{"code":0}'],
    ['带 BOM 的响应', '\uFEFF{"errorCode":0}'],
  ])('接受%s', (_name, responseText) => {
    expect(
      resolveDocumentUploadResponse({
        fallbackMessage,
        responseText,
        status: 200,
      }),
    ).toEqual({ success: true });
  });

  it('接受无响应体的 204 响应', () => {
    expect(
      resolveDocumentUploadResponse({
        fallbackMessage,
        responseText: '',
        status: 204,
      }),
    ).toEqual({ success: true });
  });

  it('返回业务错误消息', () => {
    expect(
      resolveDocumentUploadResponse({
        fallbackMessage,
        responseText: '{"errorCode":4091,"message":"文件已存在"}',
        status: 409,
      }),
    ).toEqual({
      message: '文件已存在',
      success: false,
    });
  });

  it('拒绝成功状态下的未知响应格式', () => {
    expect(
      resolveDocumentUploadResponse({
        fallbackMessage,
        responseText: 'binary-response',
        status: 200,
      }),
    ).toEqual({
      message: fallbackMessage,
      success: false,
    });
  });

  it('拒绝缺少成功错误码的空响应', () => {
    expect(
      resolveDocumentUploadResponse({
        fallbackMessage,
        responseText: '',
        status: 200,
      }),
    ).toEqual({
      message: fallbackMessage,
      success: false,
    });
  });
});
