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

import {
  encodeOptimizationStreamEvent,
  parseOptimizationStreamChunk,
  type OptimizationStreamEvent,
} from "../stream-events";

describe("optimization stream events", () => {
  it("encodes each event as one JSON line", () => {
    const event: OptimizationStreamEvent = {
      type: "draft_started",
      job_id: "job_123",
      message: "正在生成优化草稿",
    };

    expect(encodeOptimizationStreamEvent(event)).toBe(
      '{"type":"draft_started","job_id":"job_123","message":"正在生成优化草稿"}\n',
    );
  });

  it("parses chunked NDJSON while preserving incomplete lines", () => {
    const first = parseOptimizationStreamChunk(
      "",
      '{"type":"job_created","job":{"id":"job_',
    );

    expect(first.events).toEqual([]);
    expect(first.remainder).toBe('{"type":"job_created","job":{"id":"job_');

    const second = parseOptimizationStreamChunk(
      first.remainder,
      '123"}}\n{"type":"draft_started","job_id":"job_123","message":"正在生成"}\n{"type":"qa_started"',
    );

    expect(second.events).toEqual([
      { type: "job_created", job: { id: "job_123" } },
      { type: "draft_started", job_id: "job_123", message: "正在生成" },
    ]);
    expect(second.remainder).toBe('{"type":"qa_started"');
  });
});
