import { describe, expect, it } from "vitest";
import { createMockDb, testNotFound } from "../../../testing/index";
import { Transaction } from "../generated/kysely-tailordb";
import { CannotDeactivateReferenceUnitError, UnitNotFoundError } from "../lib/errors.generated";
import { baseUnitKg, baseUnitGram, baseUoMCategory, inactiveUnit } from "../testing/fixtures";
import { run } from "./deactivateUnit";

describe("deactivateUnit", () => {
  it(
    "throws when unit doesn't exist",
    testNotFound(run, { unitId: "nonexistent-unit" }, UnitNotFoundError),
  );

  it("throws when attempting to deactivate reference unit", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseUnitKg).mockReturnValueOnce(baseUoMCategory);

    const result = await run(db, {
      unitId: baseUnitKg.id,
    });

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

  // Idempotent case needs multi-mock setup, kept inline
  it("returns unit unchanged when already inactive", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(inactiveUnit).mockReturnValueOnce(baseUoMCategory);

    const result = await run(db, {
      unitId: inactiveUnit.id,
    });

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

  // Success cases
  it("deactivates active non-reference unit", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const deactivatedUnit = {
      ...baseUnitGram,
      isActive: false,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValueOnce(baseUnitGram).mockReturnValueOnce(baseUoMCategory);
    spies.update.mockReturnValue(deactivatedUnit);

    const result = await run(db, {
      unitId: baseUnitGram.id,
    });

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