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

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

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

  it("throws when category has active units", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce([baseUnitKg]); // Active units check

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

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(CategoryHasActiveUnitsError);
    }
  });

  // Idempotent case needs multi-mock setup, kept inline
  it("returns category unchanged when already inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(inactiveCategory) // Category lookup
      .mockReturnValueOnce([]); // No active units

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.uoMCategory).toEqual(inactiveCategory);
    }
    expect(spies.update).not.toHaveBeenCalled();
  });

  // Success cases
  it("deactivates active category with no active units", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedCategory = {
      ...baseUoMCategory,
      isActive: false,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select
      .mockReturnValueOnce(baseUoMCategory) // Category lookup
      .mockReturnValueOnce([]); // No active units
    spies.update.mockReturnValue(deactivatedCategory);

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

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