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 { CategoryHasActiveUnitsError, UomCategoryNotFoundError } from "../lib/errors.generated";
import { baseUoMCategory, baseUnitKg } from "../testing/fixtures";
import { run } from "./deactivateCategory";

describe("deactivateCategory", () => {
  const inactiveCategory = {
    ...baseUoMCategory,
    status: "INACTIVE" as const,
  };

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

  it("throws when category has active units", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseUoMCategory], [baseUnitKg]);

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

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

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

  // Success cases
  it("deactivates active category with no active units", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivatedCategory = {
      ...baseUoMCategory,
      status: "INACTIVE" as const,
      updatedAt: new Date("2024-01-15T00:00:00.000Z"),
    };

    mock.enqueueResults([baseUoMCategory], [], [deactivatedCategory]);

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

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