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

describe("listListingsByChannel", () => {
  it("lists listings under a channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseListing, draftListing]);

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

    expect(items).toHaveLength(2);
    expect(mock.selects[0].parameters).toContain(baseChannel.id);
    expect(mock.selects[0].sql).toMatch(/"channelId"/);
    expect(mock.selects[0].sql).toMatch(/order by .*"createdAt" desc/i);
  });

  it("filters listings by status when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseListing]);

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

    expect(items).toHaveLength(1);
    expect(mock.selects[0].parameters).toContain("ACTIVE");
    expect(mock.selects[0].sql).toMatch(/"status"/);
  });

  it("throws when channel id is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await run(mock.db, { channelId: "" });
    expectErr(result as never, ChannelIdRequiredError);
  });
});
