/**
 * @jest-environment node
 */

import { POST } from "./route";

const streamMock = jest.fn();

jest.mock("edge-tts-ts", () => ({
  Communicate: jest.fn().mockImplementation(() => ({
    stream: streamMock,
  })),
}));

describe("POST /api/tts/edge", () => {
  beforeEach(() => {
    streamMock.mockReset();
  });

  it("returns synthesized mp3 audio", async () => {
    streamMock.mockImplementation(async function* () {
      yield { type: "audio", data: new Uint8Array([1, 2]) };
      yield { type: "SentenceBoundary", offset: 0, duration: 1, text: "测试" };
      yield { type: "audio", data: new Uint8Array([3]) };
    });

    const response = await POST(
      new Request("http://localhost/api/tts/edge", {
        method: "POST",
        body: JSON.stringify({ text: "测试文本" }),
      }),
    );

    expect(response.status).toBe(200);
    expect(response.headers.get("Content-Type")).toBe("audio/mpeg");
    expect(Array.from(new Uint8Array(await response.arrayBuffer()))).toEqual([1, 2, 3]);
  });

  it("rejects empty text", async () => {
    const response = await POST(
      new Request("http://localhost/api/tts/edge", {
        method: "POST",
        body: JSON.stringify({ text: " " }),
      }),
    );

    expect(response.status).toBe(400);
    expect(await response.json()).toEqual({ error: "text is required" });
  });
});
