import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChannelOrItemInactiveError,
  ListingIdentifierRequiredError,
  MissingPriceLinkageError,
} from "../lib/errors.generated";
import {
  baseChannel,
  baseItem,
  draftListing,
  inactiveChannel,
  pausedListing,
} from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./activateListing";

describe("activateListing", () => {
  it("activates a draft listing with valid identifiers", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activated = { ...draftListing, status: "ACTIVE", updatedAt: new Date() };
    spies.select
      .mockReturnValueOnce(draftListing)
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce(baseItem);
    spies.update.mockReturnValueOnce(activated);

    const result = await run(db, { listingId: draftListing.id }, commandCtx);

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

  it("reactivates a paused listing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(pausedListing)
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce(baseItem);
    spies.update.mockReturnValueOnce({ ...pausedListing, status: "ACTIVE" });

    const result = await run(db, { listingId: pausedListing.id }, commandCtx);

    expectOk(result);
  });

  it("throws when required identifiers are missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...draftListing, sku: null, externalIdentifier: null });

    const result = await run(db, { listingId: draftListing.id }, commandCtx);

    expectErr(result, ListingIdentifierRequiredError);
  });

  it("throws when channel or item is inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(draftListing)
      .mockReturnValueOnce(inactiveChannel)
      .mockReturnValueOnce(baseItem);

    const result = await run(db, { listingId: draftListing.id }, commandCtx);

    expectErr(result, ChannelOrItemInactiveError);
  });

  it("throws when required pricing linkage is missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const listing = {
      ...draftListing,
      sku: "LIST-002",
      externalIdentifier: "AMZ-002",
      requiresPriceSync: true,
      salesPriceListId: null,
    };
    spies.select
      .mockReturnValueOnce(listing)
      .mockReturnValueOnce(baseChannel)
      .mockReturnValueOnce(baseItem);

    const result = await run(db, { listingId: listing.id }, commandCtx);

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