import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { StatusFilterRequiredError } from "../lib/errors.generated";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { baseChannelOrder, baseCompany, baseChannel } from "../testing/fixtures";
import { run } from "./listChannelOrdersByStatus";

describe("listChannelOrdersByStatus", () => {
  it("lists pending conversion channel orders", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannelOrder]);

    const result = await run(mock.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" });
    expect(mock.selects[0].parameters).toContain(baseCompany.id);
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"createdAt" desc/i);
  });

  it("lists exceptional channel orders for replay", async () => {
    const exceptionOrder = { ...baseChannelOrder, id: "channel-order-2", status: "EXCEPTION" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([exceptionOrder]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannelOrder]);

    const result = await run(mock.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 mock = createKyselyMock<Namespace["main-db"]>();

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