import { TRPCError } from "@trpc/server";
import { describe, expect, it, vi } from "vitest";
import {
  assertManagementLevelDeletable,
  assertManagementLevelGroupNameAvailable,
  assertManagementLevelNameAvailable,
  buildManagementLevelCreateData,
  buildManagementLevelGroupCreateData,
  buildManagementLevelGroupUpdateData,
  buildManagementLevelUpdateData,
} from "../router/management-level-support.js";

describe("management level support", () => {
  it("rejects duplicate group names outside the ignored id", async () => {
    const db = {
      managementLevelGroup: {
        findUnique: vi.fn().mockResolvedValue({ id: "group_existing", name: "Team Leads" }),
      },
    } as never;

    await expect(assertManagementLevelGroupNameAvailable(db, "Team Leads")).rejects.toBeInstanceOf(TRPCError);
  });

  it("rejects duplicate level names outside the ignored id", async () => {
    const db = {
      managementLevel: {
        findUnique: vi.fn().mockResolvedValue({ id: "level_existing", name: "Senior Team Lead" }),
      },
    } as never;

    await expect(assertManagementLevelNameAvailable(db, "Senior Team Lead")).rejects.toBeInstanceOf(TRPCError);
  });

  it("builds create and sparse update payloads", () => {
    expect(buildManagementLevelGroupCreateData({
      name: "Team Leads",
      targetPercentage: 0.72,
      sortOrder: 10,
    })).toEqual({
      name: "Team Leads",
      targetPercentage: 0.72,
      sortOrder: 10,
    });

    expect(buildManagementLevelGroupUpdateData({
      targetPercentage: 0.8,
    })).toEqual({
      targetPercentage: 0.8,
    });

    expect(buildManagementLevelCreateData({
      name: "Senior Team Lead",
      groupId: "group_1",
    })).toEqual({
      name: "Senior Team Lead",
      groupId: "group_1",
    });

    expect(buildManagementLevelUpdateData({
      groupId: "group_2",
    })).toEqual({
      groupId: "group_2",
    });
  });

  it("rejects deletion when a level is still assigned", () => {
    expect(() => assertManagementLevelDeletable({
      _count: { resources: 2 },
    })).toThrow(TRPCError);
  });
});
