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

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

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

  it("returns a stable assistant error when broadcast scheduledAt is invalid", async () => {
    const ctx = createToolContext({}, SystemRole.MANAGER);

    const result = await executeTool(
      "send_broadcast",
      JSON.stringify({
        title: "Office update",
        targetType: "all",
        scheduledAt: "not-a-datetime",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Invalid scheduledAt: not-a-datetime",
    });
  });

  it("returns a stable assistant error when a broadcast target resolves to no recipients", async () => {
    const create = vi.fn().mockResolvedValue({
      id: "broadcast_empty",
      title: "Office update",
      targetType: "user",
    });
    const ctx = createToolContext(
      {
        notificationBroadcast: {
          create,
        },
      },
      SystemRole.MANAGER,
    );

    const result = await executeTool(
      "send_broadcast",
      JSON.stringify({
        title: "Office update",
        targetType: "user",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "No recipients matched the broadcast target.",
    });
    expect(create).not.toHaveBeenCalled();
  });

  it("returns a stable assistant error for scheduled broadcasts with task metadata", async () => {
    const ctx = createToolContext({}, SystemRole.MANAGER);

    const result = await executeTool(
      "send_broadcast",
      JSON.stringify({
        title: "Approve later",
        targetType: "all",
        category: "TASK",
        taskAction: "approve_vacation:vac_1",
        dueDate: "2099-04-11T08:00:00.000Z",
        scheduledAt: "2099-04-10T08:00:00.000Z",
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Scheduled broadcasts with task metadata are not supported yet.",
    });
  });
});
