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

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

  it(
    "returns unit unchanged when already active",
    testIdempotent(run, { unitId: baseUnitKg.id }, baseUnitKg, "unit"),
  );

  // Success cases
  it("activates inactive unit", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activatedUnit = {
      ...inactiveUnit,
      isActive: true,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    spies.select.mockReturnValue(inactiveUnit);
    spies.update.mockReturnValue(activatedUnit);

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

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