import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { baseChannelOrder } from "../testing/fixtures";
import { expectOk } from "../testing/commandTestUtils";
import { run } from "./getChannelOrder";

describe("getChannelOrder", () => {
  it("returns channel order when found by id", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(baseChannelOrder);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(convertedOrder);

    const result = await run(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 { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce(undefined);

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

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