import { beforeEach, describe, expect, it, vi } from "vitest";
import { PermissionKey, SystemRole } from "@capakraken/shared";
import { TRPCError } from "@trpc/server";
import {
  createToolContext,
  executeTool,
} from "./assistant-tools-demand-create-test-helpers.js";

describe("assistant demand create tool - role resolution errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when the role cannot be resolved during demand creation", async () => {
    const ctx = createToolContext(
      {
        project: {
          findUnique: vi.fn()
            .mockResolvedValueOnce(null)
            .mockResolvedValueOnce({
              id: "project_1",
              name: "Project One",
              shortCode: "PROJ-1",
              status: "ACTIVE",
              responsiblePerson: "Peter Parker",
            }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        role: {
          findUnique: vi.fn().mockResolvedValue(null),
          findFirst: vi.fn().mockResolvedValue(null),
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_ALLOCATIONS],
      },
    );

    const result = await executeTool(
      "create_demand",
      JSON.stringify({
        projectId: "PROJ-1",
        roleName: "Missing Role",
        headcount: 2,
        hoursPerDay: 6,
        startDate: "2026-05-01",
        endDate: "2026-05-15",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Role not found: Missing Role",
    });
  });

  it("returns a generic assistant error when role resolution fails internally during demand creation", async () => {
    const demandCreate = vi.fn();
    const ctx = createToolContext(
      {
        project: {
          findUnique: vi.fn()
            .mockResolvedValueOnce(null)
            .mockResolvedValueOnce({
              id: "project_1",
              name: "Project One",
              shortCode: "PROJ-1",
              status: "ACTIVE",
              responsiblePerson: "Peter Parker",
            }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        role: {
          findUnique: vi.fn().mockRejectedValue(
            new TRPCError({
              code: "INTERNAL_SERVER_ERROR",
              message: "role resolver connection exhausted",
            }),
          ),
        },
        demandRequirement: {
          create: demandCreate,
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_ALLOCATIONS],
      },
    );

    const result = await executeTool(
      "create_demand",
      JSON.stringify({
        projectId: "PROJ-1",
        roleName: "Designer",
        headcount: 2,
        hoursPerDay: 6,
        startDate: "2026-05-01",
        endDate: "2026-05-15",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "The tool could not complete due to an internal error.",
    });
    expect(demandCreate).not.toHaveBeenCalled();
  });
});
