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 finalization errors", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("returns a stable assistant error when broadcast finalization loses the broadcast row", async () => {
    const txCreateBroadcast = vi.fn().mockResolvedValue({
      id: "broadcast_missing_after_create",
      title: "Office update",
      targetType: "all",
    });
    const txCreateNotification = vi.fn().mockResolvedValue({ id: "notification_2", userId: "user_2" });
    const txUpdateBroadcast = vi.fn().mockRejectedValue(
      Object.assign(new Error("Record to update not found"), {
        code: "P2025",
        meta: { modelName: "NotificationBroadcast" },
      }),
    );
    const tx = {
      notificationBroadcast: {
        create: txCreateBroadcast,
        update: txUpdateBroadcast,
      },
      notification: {
        create: txCreateNotification,
      },
    };
    const ctx = createToolContext(
      {
        user: {
          findMany: vi.fn().mockResolvedValue([{ id: "user_2" }]),
        },
        $transaction: vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx)),
        notificationBroadcast: {
          create: vi.fn(),
          update: vi.fn(),
        },
        notification: {
          create: vi.fn(),
        },
      },
      SystemRole.MANAGER,
    );

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

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

  it("returns a stable assistant error when broadcast finalization loses the row without prisma metadata", async () => {
    const tx = {
      notificationBroadcast: {
        create: vi.fn().mockResolvedValue({
          id: "broadcast_missing_after_create_generic",
          title: "Office update",
          targetType: "all",
        }),
        update: vi.fn().mockRejectedValue(
          Object.assign(new Error("Record to update not found"), {
            code: "P2025",
          }),
        ),
      },
      notification: {
        create: vi.fn().mockResolvedValue({ id: "notification_2", userId: "user_2" }),
      },
    };
    const ctx = createToolContext(
      {
        user: {
          findMany: vi.fn().mockResolvedValue([{ id: "user_2" }]),
        },
        $transaction: vi.fn(async (callback: (db: typeof tx) => Promise<unknown>) => callback(tx)),
        notificationBroadcast: {
          create: vi.fn(),
          update: vi.fn(),
        },
        notification: {
          create: vi.fn(),
        },
      },
      SystemRole.MANAGER,
    );

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

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