import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidStateTransitionError, ProductNotFoundError } from "../lib/errors.generated";
import { baseActiveProduct, baseArchivedProduct } from "../testing/fixtures";
import { run } from "./reactivateProduct";

describe("reactivateProduct", () => {
  it("returns error when product not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const result = await mock.withTx((trx) => run(trx, { id: "nonexistent" }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("returns error when not in ARCHIVED status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseActiveProduct }]);
    const result = await mock.withTx((trx) => run(trx, { id: "product-2" }));
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateTransitionError);
    }
  });

  it("reactivates ARCHIVED product to ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const reactivated = { ...baseArchivedProduct, status: "ACTIVE" };
    mock.enqueueResults([{ ...baseArchivedProduct }], [reactivated]);
    const result = await mock.withTx((trx) => run(trx, { id: "product-3" }));
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.status).toBe("ACTIVE");
    }
  });
});
