import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { testNotFound, testIdempotent } from "../../../testing";
import type { Namespace } from "../generated/kysely-tailordb";
import { UomCategoryNotFoundError } from "../lib/errors.generated";
import { baseUoMCategory } from "../testing/fixtures";
import { run } from "./activateCategory";

describe("activateCategory", () => {
  const inactiveCategory = {
    ...baseUoMCategory,
    status: "INACTIVE" as const,
  };

  it(
    "throws when category doesn't exist",
    testNotFound(run, { categoryId: "nonexistent-category" }, UomCategoryNotFoundError),
  );

  it(
    "returns category unchanged when already active",
    testIdempotent(run, { categoryId: baseUoMCategory.id }, baseUoMCategory, "uoMCategory"),
  );

  // Success cases
  it("activates inactive category", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activatedCategory = {
      ...inactiveCategory,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([inactiveCategory], [activatedCategory]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        categoryId: inactiveCategory.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.status).toBe("ACTIVE");
      expect(result.value.uoMCategory.updatedAt).not.toBeNull();
    }
    expect(mock.updates).toHaveLength(1);
  });
});
