import { describe, expect, it } from "vitest";
import { createMockDb, testNotFound, testIdempotent } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { UomCategoryNotFoundError } from "../lib/errors.generated";
import { baseUoMCategory } from "../testing/fixtures";
import { run } from "./activateCategory";

describe("activateCategory", () => {
  const inactiveCategory = {
    ...baseUoMCategory,
    isActive: false,
  };

  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 { db, spies } = createMockDb<Transaction>();
    const activatedCategory = {
      ...inactiveCategory,
      isActive: true,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValue(inactiveCategory);
    spies.update.mockReturnValue(activatedCategory);

    const result = await run(db, {
      categoryId: inactiveCategory.id,
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory.isActive).toBe(true);
      expect(result.value.uoMCategory.updatedAt).not.toBeNull();
    }
    expect(spies.update).toHaveBeenCalled();
  });
});
