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 { 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 mock = createKyselyMock<Namespace["main-db"]>();
    const activatedUnit = {
      ...inactiveUnit,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([inactiveUnit], [activatedUnit]);

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

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