import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ChannelOrItemInactiveError,
  ListingIdentifierRequiredError,
  MissingPriceLinkageError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseChannel,
  baseItem,
  draftListing,
  inactiveChannel,
  pausedListing,
} from "../testing/fixtures";
import { mockItemQueries } from "../testing/moduleMocks";
import { run } from "./activateListing";

describe("activateListing", () => {
  it("activates a draft listing with valid identifiers", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activated = { ...draftListing, status: "ACTIVE", updatedAt: new Date() };
    mock.enqueueResults([draftListing], [baseChannel], [activated]);

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: draftListing.id }, commandCtx, mockItemQueries([baseItem])),
    );

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

  it("reactivates a paused listing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([pausedListing], [baseChannel], [{ ...pausedListing, status: "ACTIVE" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: pausedListing.id }, commandCtx, mockItemQueries([baseItem])),
    );

    expectOk(result);
  });

  it("throws when required identifiers are missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...draftListing, sku: null, externalIdentifier: null }]);

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: draftListing.id }, commandCtx, mockItemQueries([baseItem])),
    );

    expectErr(result, ListingIdentifierRequiredError);
  });

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

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: draftListing.id }, commandCtx, mockItemQueries([baseItem])),
    );

    expectErr(result, ChannelOrItemInactiveError);
  });

  it("throws when required pricing linkage is missing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const listing = {
      ...draftListing,
      sku: "LIST-002",
      externalIdentifier: "AMZ-002",
      requiresPriceSync: true,
      salesPriceListId: null,
    };
    mock.enqueueResults([listing], [baseChannel]);

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: listing.id }, commandCtx, mockItemQueries([baseItem])),
    );

    expectErr(result, MissingPriceLinkageError);
  });
});
