import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { expectOk } from "../testing/commandTestUtils";
import { baseChannelOrder } from "../testing/fixtures";
import { run } from "./getChannelOrder";

describe("getChannelOrder", () => {
  it("returns channel order when found by id", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannelOrder]);

    const result = await run(mock.db, { id: baseChannelOrder.id });
    const { channelOrder } = expectOk<{
      channelOrder: { id: string; rawPayload: Record<string, unknown> | null };
    }>(result as never);

    expect(channelOrder).not.toBeNull();
    expect(channelOrder.id).toBe(baseChannelOrder.id);
    expect(channelOrder.rawPayload).toEqual({ orderId: "EXT-001" });
  });

  it("returns channel order with linked sales-order reference when converted", async () => {
    const convertedOrder = {
      ...baseChannelOrder,
      id: "channel-order-2",
      status: "CONVERTED" as const,
      salesOrderId: "sales-order-1",
    };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([convertedOrder]);

    const result = await run(mock.db, { id: convertedOrder.id });
    const { channelOrder } = expectOk<{
      channelOrder: { salesOrderId: string };
    }>(result as never);

    expect(channelOrder.salesOrderId).toBe("sales-order-1");
  });

  it("returns null when channel order is not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await run(mock.db, { id: "nonexistent-id" });
    const { channelOrder } = expectOk<{ channelOrder: unknown }>(result as never);

    expect(channelOrder).toBeNull();
  });
});
