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-resource-admin-create-test-helpers.js";

describe("assistant resource admin create tools - persistence errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a generic assistant error when role resolution fails internally during resource creation", async () => {
    const resourceCreate = vi.fn();
    const ctx = createToolContext(
      {
        resource: {
          findFirst: vi.fn().mockResolvedValue(null),
          create: resourceCreate,
        },
        role: {
          findUnique: vi.fn().mockRejectedValue(
            new TRPCError({
              code: "INTERNAL_SERVER_ERROR",
              message: "role resolver connection exhausted",
            }),
          ),
        },
        assignment: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        demandRequirement: {
          findMany: vi.fn().mockResolvedValue([]),
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "create_resource",
      JSON.stringify({
        eid: "EMP-500",
        displayName: "Role Failure",
        email: "role-failure@example.com",
        lcrCents: 8000,
        roleName: "Designer",
      }),
      ctx,
    );

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

  it("returns a stable assistant error when the selected resource role disappears before creation", async () => {
    const resourceCreate = vi.fn().mockRejectedValue({
      code: "P2003",
      message: "Foreign key constraint failed",
      meta: { field_name: "Resource_roleId_fkey" },
    });
    const ctx = createToolContext(
      {
        resource: {
          findFirst: vi.fn().mockResolvedValue(null),
          create: resourceCreate,
        },
        role: {
          findUnique: vi.fn().mockResolvedValue({ id: "role_1", name: "Designer" }),
          findFirst: vi.fn().mockResolvedValue(null),
        },
        assignment: {
          findMany: vi.fn().mockResolvedValue([]),
        },
        demandRequirement: {
          findMany: vi.fn().mockResolvedValue([]),
        },
      },
      {
        userRole: SystemRole.ADMIN,
        permissions: [PermissionKey.MANAGE_RESOURCES],
      },
    );

    const result = await executeTool(
      "create_resource",
      JSON.stringify({
        eid: "EMP-002",
        displayName: "Carol Danvers",
        email: "carol@example.com",
        lcrCents: 8000,
        roleName: "Designer",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Role not found with the given criteria.",
    });
  });
});
