import { describe, expect, it } from "vitest";
import { getUserFacingErrorMessage } from "./errors";

describe("getUserFacingErrorMessage", () => {
  it("在 message 很短时直接返回", () => {
    expect(getUserFacingErrorMessage(new Error("未登录"), "fallback")).toBe("未登录");
  });

  it("能从 Convex 的长错误中提取 Uncaught Error 之后的消息", () => {
    const err = new Error(
      "[CONVEX M(users:setMyUsername)] [Request ID: xxx] Server Error Uncaught Error: 未登录 at handler (./convex/users.ts:41:10) Called by client",
    );
    expect(getUserFacingErrorMessage(err, "fallback")).toBe("未登录");
  });

  it("能从包含 Error: 的错误中提取关键信息", () => {
    const err = new Error("Server Error Error: 用户名已被占用 at handler (./convex/users.ts:48:7)");
    expect(getUserFacingErrorMessage(err, "fallback")).toBe("用户名已被占用");
  });

  it("字符串错误也能直接展示", () => {
    expect(getUserFacingErrorMessage("  保存失败  ", "fallback")).toBe("保存失败");
  });

  it("无法解析时返回 fallback", () => {
    expect(getUserFacingErrorMessage({ foo: "bar" }, "fallback")).toBe("fallback");
  });
});
