import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { DB } from "../generated/kysely-tailordb";
import { ChannelIdRequiredError } from "../lib/errors.generated";
import { baseChannel, baseListing, draftListing } from "../testing/fixtures";
import { expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./listListingsByChannel";

describe("listListingsByChannel", () => {
  it("lists listings under a channel", async () => {
    const { db, spies } = createMockDb<DB>();
    spies.select.mockReturnValueOnce([baseListing, draftListing]);

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

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

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

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

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

  it("throws when channel id is missing", async () => {
    const { db } = createMockDb<DB>();

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