import { TRPCError } from "@trpc/server";
import { describe, expect, it, vi } from "vitest";
import {
  assertUtilizationCategoryCodeAvailable,
  buildUtilizationCategoryCreateData,
  buildUtilizationCategoryListWhere,
  buildUtilizationCategoryUpdateData,
  unsetDefaultUtilizationCategory,
} from "../router/utilization-category-support.js";

describe("utilization category support", () => {
  it("builds list filters", () => {
    expect(buildUtilizationCategoryListWhere({ isActive: true })).toEqual({
      isActive: true,
    });
  });

  it("rejects duplicate codes outside the ignored id", async () => {
    const db = {
      utilizationCategory: {
        findUnique: vi.fn().mockResolvedValue({ id: "util_existing", code: "CHARGEABLE" }),
      },
    } as never;

    await expect(assertUtilizationCategoryCodeAvailable(db, "CHARGEABLE")).rejects.toBeInstanceOf(TRPCError);
  });

  it("unsets the current default with and without an ignored id", async () => {
    const db = {
      utilizationCategory: {
        updateMany: vi.fn().mockResolvedValue({ count: 1 }),
      },
    } as never;

    await unsetDefaultUtilizationCategory(db);
    await unsetDefaultUtilizationCategory(db, "util_keep");

    expect(db.utilizationCategory.updateMany).toHaveBeenNthCalledWith(1, {
      where: { isDefault: true },
      data: { isDefault: false },
    });
    expect(db.utilizationCategory.updateMany).toHaveBeenNthCalledWith(2, {
      where: { isDefault: true, id: { not: "util_keep" } },
      data: { isDefault: false },
    });
  });

  it("builds create and sparse update payloads", () => {
    expect(buildUtilizationCategoryCreateData({
      code: "CHARGEABLE",
      name: "Chargeable",
      description: "Revenue-generating project work",
      sortOrder: 1,
      isDefault: true,
    })).toEqual({
      code: "CHARGEABLE",
      name: "Chargeable",
      description: "Revenue-generating project work",
      sortOrder: 1,
      isDefault: true,
    });

    expect(buildUtilizationCategoryUpdateData({
      description: null,
      isActive: false,
      isDefault: false,
    })).toEqual({
      description: null,
      isActive: false,
      isDefault: false,
    });
  });
});
