import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  DuplicateListingIdentityError,
  ItemNotActiveError,
} from "../lib/errors.generated";
import {
  baseChannel,
  baseItem,
  baseListing,
  draftListing,
  inactiveItem,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createListing";

describe("createListing", () => {
  it("creates a draft listing for an active item and valid channel", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce([]);
    spies.insert.mockReturnValueOnce(draftListing);

    const result = await run(
      db,
      {
        channelId: baseChannel.id,
        itemId: baseItem.id,
        sku: baseListing.sku ?? undefined,
        externalIdentifier: baseListing.externalIdentifier,
      },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.listing.status).toBe("DRAFT");
  });

  it("throws when channel does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { channelId: baseChannel.id, itemId: baseItem.id, sku: "SKU-1" },
      commandCtx,
    );

    expectErr(result, ChannelNotFoundError);
  });

  it("throws when item is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseChannel).mockReturnValueOnce(inactiveItem);

    const result = await run(
      db,
      { channelId: baseChannel.id, itemId: inactiveItem.id, sku: "SKU-1" },
      commandCtx,
    );

    expectErr(result, ItemNotActiveError);
  });

  it("throws when listing identity conflicts within the channel", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce(baseItem)
      .mockReturnValueOnce([baseListing]);

    const result = await run(
      db,
      {
        channelId: baseChannel.id,
        itemId: baseItem.id,
        externalIdentifier: baseListing.externalIdentifier,
      },
      commandCtx,
    );

    expectErr(result, DuplicateListingIdentityError);
  });
});
