import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";

vi.mock("@capakraken/application", async (importOriginal) => {
  const actual = await importOriginal<typeof import("@capakraken/application")>();
  return {
    ...actual,
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
  };
});

import { executeTool } from "../router/assistant-tools.js";
import { createToolContext } from "./assistant-tools-user-admin-test-helpers.js";

describe("assistant user admin resource linking not-found errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable error when linking a missing user to a resource", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "link_user_resource",
      JSON.stringify({ userId: "user_missing", resourceId: "res_1" }),
      ctx,
    );

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

  it("returns a stable error when linking a user to a missing resource", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
        },
        resource: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "link_user_resource",
      JSON.stringify({ userId: "user_1", resourceId: "res_missing" }),
      ctx,
    );

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

  it("returns a stable error when linking a user to a resource that disappears during persistence", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValue({ id: "user_1" }),
        },
        resource: {
          findUnique: vi.fn().mockResolvedValueOnce({ id: "res_1", userId: null }).mockResolvedValueOnce(null),
          updateMany: vi.fn().mockResolvedValueOnce({ count: 0 }).mockResolvedValueOnce({ count: 0 }),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "link_user_resource",
      JSON.stringify({ userId: "user_1", resourceId: "res_1" }),
      ctx,
    );

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

  it("returns a stable error when linking a user after the user disappears during persistence", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValueOnce({ id: "user_1" }).mockResolvedValueOnce(null),
        },
        resource: {
          findUnique: vi
            .fn()
            .mockResolvedValueOnce({ id: "res_1", userId: null })
            .mockResolvedValueOnce({ id: "res_1", userId: null }),
          updateMany: vi.fn().mockResolvedValueOnce({ count: 0 }).mockResolvedValueOnce({ count: 0 }),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "link_user_resource",
      JSON.stringify({ userId: "user_1", resourceId: "res_1" }),
      ctx,
    );

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

  it("returns a stable error when linking a user after the user disappears and prisma reports an array target", async () => {
    const ctx = createToolContext(
      {
        user: {
          findUnique: vi.fn().mockResolvedValueOnce({ id: "user_1" }).mockResolvedValueOnce(null),
        },
        resource: {
          findUnique: vi
            .fn()
            .mockResolvedValueOnce({ id: "res_1", userId: null })
            .mockResolvedValueOnce({ id: "res_1", userId: null }),
          updateMany: vi.fn().mockResolvedValueOnce({ count: 0 }).mockResolvedValueOnce({ count: 0 }),
        },
      },
      SystemRole.ADMIN,
    );

    const result = await executeTool(
      "link_user_resource",
      JSON.stringify({ userId: "user_1", resourceId: "res_1" }),
      ctx,
    );

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