import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { InvalidListingStatusError } from "../lib/errors.generated";
import { baseListing, draftListing, pausedListing } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./pauseListing";

describe("pauseListing", () => {
  it("pauses an active listing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseListing);
    spies.update.mockReturnValueOnce(pausedListing);

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

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

  it("preserves identifiers when listing is paused", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseListing);
    spies.update.mockReturnValueOnce(pausedListing);

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

    const value = expectOk(result);
    expect(value.listing.externalIdentifier).toBe(baseListing.externalIdentifier);
  });

  it("throws when listing is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftListing);

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

    expectErr(result, InvalidListingStatusError);
  });
});
