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 { draftListing, pausedListing, retiredListing } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./retireListing";

describe("retireListing", () => {
  it("retires a draft or active listing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const retired = { ...draftListing, status: "RETIRED", updatedAt: new Date() };
    spies.select.mockReturnValueOnce(draftListing);
    spies.update.mockReturnValueOnce(retired);

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

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

  it("preserves historical references after retirement", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const retired = { ...pausedListing, status: "RETIRED", updatedAt: new Date() };
    spies.select.mockReturnValueOnce(pausedListing);
    spies.update.mockReturnValueOnce(retired);

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

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

  it("throws when listing status does not allow retirement", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(retiredListing);

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

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