import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { StatusFilterRequiredError } from "../lib/errors.generated";
import { baseChannelOrder, baseCompany, baseChannel } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listChannelOrdersByStatus";

describe("listChannelOrdersByStatus", () => {
  it("lists pending conversion channel orders", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseChannelOrder]);

    const result = await run(db, {
      companyId: baseCompany.id,
      statuses: ["PENDING_CONVERSION"],
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect((items[0] as { rawPayload: unknown }).rawPayload).toEqual({ orderId: "EXT-001" });
  });

  it("lists exceptional channel orders for replay", async () => {
    const exceptionOrder = { ...baseChannelOrder, id: "channel-order-2", status: "EXCEPTION" };
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([exceptionOrder]);

    const result = await run(db, {
      companyId: baseCompany.id,
      statuses: ["EXCEPTION"],
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("filters results by channel when provided", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseChannelOrder]);

    const result = await run(db, {
      companyId: baseCompany.id,
      statuses: ["PENDING_CONVERSION"],
      channelId: baseChannel.id,
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
  });

  it("throws when no status filter is provided", async () => {
    const { db } = createMockDb<DB>();

    const result = await run(db, { companyId: baseCompany.id, statuses: [] });
    expectErr(result as never, StatusFilterRequiredError);
  });
});
