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,
    approveEstimateVersion: vi.fn(),
    cloneEstimate: vi.fn(),
    commitDispoImportBatch: vi.fn(),
    countPlanningEntries: vi.fn().mockResolvedValue({ countsByRoleId: new Map() }),
    createEstimateExport: vi.fn(),
    createEstimatePlanningHandoff: vi.fn(),
    createEstimateRevision: vi.fn(),
    assessDispoImportReadiness: vi.fn(),
    loadResourceDailyAvailabilityContexts: vi.fn().mockResolvedValue(new Map()),
    getDashboardDemand: vi.fn().mockResolvedValue([]),
    getDashboardBudgetForecast: vi.fn().mockResolvedValue([]),
    getDashboardOverview: vi.fn(),
    getDashboardSkillGapSummary: vi.fn().mockResolvedValue({
      roleGaps: [],
      totalOpenPositions: 0,
      skillSupplyTop10: [],
      resourcesByRole: [],
    }),
    getDashboardProjectHealth: vi.fn().mockResolvedValue([]),
    getDashboardPeakTimes: vi.fn().mockResolvedValue([]),
    getDashboardTopValueResources: vi.fn().mockResolvedValue([]),
    getEstimateById: vi.fn(),
    listAssignmentBookings: vi.fn().mockResolvedValue([]),
    stageDispoImportBatch: vi.fn(),
    submitEstimateVersion: vi.fn(),
    updateEstimateDraft: vi.fn(),
  };
});

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

describe("assistant broadcast send tools", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("creates and sends a broadcast through the notification router", async () => {
    const tx = {
      notificationBroadcast: {
        create: vi.fn().mockResolvedValue({
          id: "broadcast_1",
          title: "Office update",
          targetType: "user",
          createdAt: new Date("2026-03-30T09:00:00.000Z"),
        }),
        update: vi.fn().mockResolvedValue({
          id: "broadcast_1",
          recipientCount: 1,
        }),
      },
      notification: {
        create: vi.fn().mockResolvedValue({ id: "notification_2", userId: "user_2" }),
      },
    };
    const db = {
      notificationBroadcast: {
        create: vi.fn(),
        update: vi.fn(),
      },
      notification: {
        create: vi.fn(),
      },
      $transaction: vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx)),
    };
    const ctx = createToolContext(db, SystemRole.ADMIN);

    const result = await executeTool(
      "send_broadcast",
      JSON.stringify({
        title: "Office update",
        body: "New schedule",
        targetType: "user",
        targetValue: "user_2",
        category: "TASK",
        priority: "HIGH",
        channel: "in_app",
        dueDate: "2026-04-04T10:00:00.000Z",
      }),
      ctx,
    );

    expect(tx.notificationBroadcast.create).toHaveBeenCalledWith({
      data: expect.objectContaining({
        senderId: "user_1",
        title: "Office update",
        body: "New schedule",
        category: "TASK",
        priority: "HIGH",
        channel: "in_app",
        targetType: "user",
        targetValue: "user_2",
      }),
    });
    expect(tx.notification.create).toHaveBeenCalledWith({
      data: expect.objectContaining({
        userId: "user_2",
        type: "BROADCAST_TASK",
        title: "Office update",
        body: "New schedule",
        category: "TASK",
        priority: "HIGH",
        channel: "in_app",
        sourceId: "broadcast_1",
        senderId: "user_1",
        taskStatus: "OPEN",
        dueDate: new Date("2026-04-04T10:00:00.000Z"),
      }),
    });
    expect(tx.notificationBroadcast.update).toHaveBeenCalledWith({
      where: { id: "broadcast_1" },
      data: expect.objectContaining({
        sentAt: expect.any(Date),
        recipientCount: 1,
      }),
    });
    expect(JSON.parse(result.content)).toEqual(
      expect.objectContaining({
        success: true,
        broadcastId: "broadcast_1",
        recipientCount: 1,
        message: 'Broadcast "Office update" created.',
      }),
    );
    expect(result.action).toEqual({
      type: "invalidate",
      scope: ["notification"],
    });
  });
});
