import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ChannelNotFoundError,
  DuplicateListingIdentityError,
  ItemNotActiveError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseChannel,
  baseItem,
  baseListing,
  draftListing,
  inactiveItem,
} from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./createListing";

describe("createListing", () => {
  it("creates a draft listing for an active item and valid channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [], [draftListing]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          channelId: baseChannel.id,
          itemId: baseItem.id,
          sku: baseListing.sku ?? undefined,
          externalIdentifier: baseListing.externalIdentifier,
        },
        commandCtx,
        mockItemQueries([baseItem]),
      ),
    );

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

  it("throws when channel does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { channelId: baseChannel.id, itemId: baseItem.id, sku: "SKU-1" },
        commandCtx,
        mockItemQueries([baseItem]),
      ),
    );

    expectErr(result, ChannelNotFoundError);
  });

  it("throws when item is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { channelId: baseChannel.id, itemId: inactiveItem.id, sku: "SKU-1" },
        commandCtx,
        mockItemQueries([inactiveItem]),
      ),
    );

    expectErr(result, ItemNotActiveError);
  });

  it("throws when listing identity conflicts within the channel", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseChannel], [baseListing]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          channelId: baseChannel.id,
          itemId: baseItem.id,
          externalIdentifier: baseListing.externalIdentifier,
        },
        commandCtx,
        mockItemQueries([baseItem]),
      ),
    );

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