import { 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, withUserLookup } from "./assistant-tools-notification-test-helpers.js";

describe("assistant broadcast detail tools", () => {
  it("reads broadcast details for managers and keeps the manager-only permission boundary", async () => {
    const db = withUserLookup(
      {
        notificationBroadcast: {
          findUnique: vi.fn().mockResolvedValue({
            id: "broadcast_7",
            title: "Org update",
            sender: { id: "user_mgr", name: "Manager", email: "mgr@example.com" },
          }),
        },
      },
      "user_mgr",
    );
    const managerCtx = createToolContext(db, SystemRole.MANAGER);
    const userCtx = createToolContext(
      withUserLookup({
        notificationBroadcast: {
          findUnique: vi.fn(),
        },
      }),
      SystemRole.USER,
    );

    const allowed = await executeTool(
      "get_broadcast_detail",
      JSON.stringify({ id: "broadcast_7" }),
      managerCtx,
    );
    const denied = await executeTool(
      "get_broadcast_detail",
      JSON.stringify({ id: "broadcast_7" }),
      userCtx,
    );

    expect(db.notificationBroadcast.findUnique).toHaveBeenCalledWith({
      where: { id: "broadcast_7" },
      include: {
        sender: { select: { id: true, name: true, email: true } },
      },
    });
    expect(JSON.parse(allowed.content)).toEqual(
      expect.objectContaining({
        id: "broadcast_7",
        title: "Org update",
      }),
    );
    expect(JSON.parse(denied.content)).toEqual(
      expect.objectContaining({
        error: "You do not have permission to perform this action.",
      }),
    );
  });

  it("returns a stable assistant error for a missing broadcast", async () => {
    const ctx = createToolContext(
      withUserLookup({
        notificationBroadcast: {
          findUnique: vi.fn().mockResolvedValue(null),
        },
      }),
      SystemRole.MANAGER,
    );

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

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