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

import { HttpTicketGateway } from "./streamGateways";
import type { HttpInvoker } from "./httpInvoker";
import type { WsLiveClient } from "./wsLiveClient";

function gateway(result: unknown): {
  gw: HttpTicketGateway;
  invoke: ReturnType<typeof vi.fn>;
} {
  const invoke = vi.fn().mockResolvedValue(result);
  const http = { invoke } as unknown as HttpInvoker;
  const ws = {} as unknown as WsLiveClient;
  return { gw: new HttpTicketGateway(http, ws), invoke };
}

describe("HttpTicketGateway normalization", () => {
  it("normalizes legacy ticket list rows that omit assignedAgentIds and createdBy", async () => {
    const { gw } = gateway({
      items: [
        {
          ref: "#12",
          path: ".ideai/tickets/12/issue.md",
          title: "Legacy row",
          status: "open",
          priority: "medium",
          updatedAt: 1,
        },
      ],
    });

    const list = await gw.list("proj-1");

    expect(list.items[0]?.assignedAgentIds).toEqual([]);
    expect(list.items[0]?.createdBy).toEqual({ kind: "user" });
  });

  it("normalizes legacy ticket payloads that omit array fields and actors", async () => {
    const { gw } = gateway({
      id: "issue-1",
      ref: "#12",
      number: 12,
      title: "Legacy",
      description: "",
      status: "open",
      priority: "medium",
      createdAt: 1,
      updatedAt: 1,
      version: 1,
    });

    const ticket = await gw.read("proj-1", "#12", true);

    expect(ticket.links).toEqual([]);
    expect(ticket.assignedAgentIds).toEqual([]);
    expect(ticket.attachments).toEqual([]);
    expect(ticket.createdBy).toEqual({ kind: "user" });
    expect(ticket.updatedBy).toEqual({ kind: "user" });
  });

  it("normalizes malformed ticket actors", async () => {
    const { gw } = gateway({
      id: "issue-1",
      ref: "#12",
      number: 12,
      title: "Legacy",
      description: "",
      status: "open",
      priority: "medium",
      createdBy: { kind: "agent" },
      updatedBy: { kind: "unknown" },
      createdAt: 1,
      updatedAt: 1,
      version: 1,
    });

    const ticket = await gw.read("proj-1", "#12", true);

    expect(ticket.createdBy).toEqual({ kind: "user" });
    expect(ticket.updatedBy).toEqual({ kind: "user" });
  });
});
