import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidListingStatusError } from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { draftListing, pausedListing, retiredListing } from "../testing/fixtures";
import { run } from "./retireListing";

describe("retireListing", () => {
  it("retires a draft or active listing", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const retired = { ...draftListing, status: "RETIRED", updatedAt: new Date() };
    mock.enqueueResults([draftListing], [retired]);

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

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

  it("preserves historical references after retirement", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const retired = { ...pausedListing, status: "RETIRED", updatedAt: new Date() };
    mock.enqueueResults([pausedListing], [retired]);

    const result = await mock.withTx((trx) =>
      run(trx, { 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([retiredListing]);

    const result = await mock.withTx((trx) =>
      run(trx, { listingId: retiredListing.id }, commandCtx),
    );

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