import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { testNotFound } from "../../../testing";
import type { Namespace } 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseUnitKg], [baseUoMCategory]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveUnit], [baseUoMCategory]);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.unit).toEqual(inactiveUnit);
    }
    expect(mock.updates).toHaveLength(0);
  });

  // Success cases
  it("deactivates active non-reference unit", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedUnit = {
      ...baseUnitGram,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([baseUnitGram], [baseUoMCategory], [deactivatedUnit]);

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

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