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

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-audit-task-test-helpers.js";

describe("assistant audit error and access guards", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns stable assistant errors for missing audit log entries", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          findUniqueOrThrow: vi.fn().mockRejectedValue(
            new TRPCError({ code: "NOT_FOUND", message: "Audit log entry not found" }),
          ),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "get_audit_log_entry",
      JSON.stringify({ id: "audit_missing" }),
      ctx,
    );

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

  it("enforces controller access for audit tools via the backing router", async () => {
    const ctx = createToolContext(
      {
        auditLog: {
          findMany: vi.fn(),
        },
      },
      { userRole: SystemRole.USER },
    );

    const result = await executeTool(
      "query_change_history",
      JSON.stringify({ entityType: "Project" }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        error: "You do not have permission to perform this action.",
      }),
    );
  });
});
