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

import { buildExtractMaterialsErrorResponse } from "./extract-materials-errors.ts";

describe("buildExtractMaterialsErrorResponse", () => {
  it("maps LLM rate limit failures to HTTP 429 structured JSON", () => {
    const response = buildExtractMaterialsErrorResponse(
      new Error("物料提取失败 (低压热缩附件.docx): 429 您的账户已达到速率限制，请您控制请求频率"),
      {
        batchId: "CG-20260426-014",
        sourceFileId: "source-file-001",
        sourceFileName: "低压热缩附件.docx",
        extractionModel: "glm-5.1",
      },
    );

    expect(response.status).toBe(429);
    expect(response.body).toEqual({
      success: false,
      code: "LLM_RATE_LIMIT",
      retryable: true,
      error: "glm-5.1 调用达到速率限制，请稍后重试",
      raw_error: "物料提取失败 (低压热缩附件.docx): 429 您的账户已达到速率限制，请您控制请求频率",
      batch_id: "CG-20260426-014",
      source_file_id: "source-file-001",
      source_file_name: "低压热缩附件.docx",
    });
  });

  it.each([
    ["模型请求超时", "LLM_TIMEOUT", true],
    ["文档提取模型返回内容不是合法 JSON", "LLM_INVALID_RESPONSE", false],
    ["DOCUMENT_OCR_LLM_PROVIDER=deepseek 的官方 API 不支持图片输入", "LLM_PROVIDER_UNSUPPORTED_INPUT", false],
    ["[procurement_materials] 写入文档识别物料失败: permission denied", "DB_WRITE_FAILED", false],
  ])("classifies %s", (message, code, retryable) => {
    const response = buildExtractMaterialsErrorResponse(new Error(message), {
      batchId: "batch-001",
      sourceFileId: "source-file-001",
      sourceFileName: "清单.pdf",
    });

    expect(response.status).toBe(500);
    expect(response.body).toMatchObject({
      success: false,
      code,
      retryable,
      raw_error: message,
      batch_id: "batch-001",
      source_file_id: "source-file-001",
      source_file_name: "清单.pdf",
    });
  });
});
