import { describe, expect, it } from "vitest";
import { PatchableTextStream } from "../../src/feishu/textStream.js";

describe("PatchableTextStream", () => {
  it("creates only one initial message when deltas arrive while create is pending", async () => {
    const creates: string[] = [];
    const patches: string[] = [];
    let resolveCreate: ((id: string) => void) | undefined;
    const firstCreate = new Promise<string>((resolve) => {
      resolveCreate = resolve;
    });
    const stream = new PatchableTextStream(
      {
        create: async (text) => {
          creates.push(text);
          return firstCreate;
        },
        patch: async (_messageId, text) => {
          patches.push(text);
        },
      },
      { patchIntervalMs: 0 },
    );

    stream.append("我目前运行在");
    await Promise.resolve();
    stream.append(" Claude Sonnet");
    resolveCreate?.("msg-1");
    await stream.finish("我目前运行在 Claude Sonnet");

    expect(creates).toEqual(["我目前运行在"]);
    expect(patches.at(-1)).toBe("我目前运行在 Claude Sonnet");
  });

  it("sends a fallback message when no stream delta arrived", async () => {
    const creates: string[] = [];
    const stream = new PatchableTextStream({
      create: async (text) => {
        creates.push(text);
        return "msg-1";
      },
      patch: async () => {},
    });

    await stream.finish("完整回复");

    expect(creates).toEqual(["完整回复"]);
  });
});
