import { beforeEach, describe, expect, it, vi } from "vitest";
import { SystemRole } from "@capakraken/shared";
import {
  createToolContext,
  executeTool,
  resetAssistantImportToolTestState,
} from "./assistant-tools-import-dispo-webhooks-test-helpers.js";

describe("assistant webhook tools - errors", () => {
  beforeEach(async () => {
    await resetAssistantImportToolTestState();
  });

  it("returns stable assistant errors for missing webhooks", async () => {
    const commands = [
      ["get_webhook", { id: "wh_missing" }],
      ["update_webhook", { id: "wh_missing", data: { name: "Renamed" } }],
      ["delete_webhook", { id: "wh_missing" }],
      ["test_webhook", { id: "wh_missing" }],
    ] as const;

    for (const [toolName, payload] of commands) {
      const ctx = createToolContext(
        {
          webhook: {
            findUnique: vi.fn().mockResolvedValue(null),
          },
        },
        { userRole: SystemRole.ADMIN },
      );

      const result = await executeTool(toolName, JSON.stringify(payload), ctx);

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

  it("returns a stable assistant error for invalid webhook creation input", async () => {
    const ctx = createToolContext(
      {
        webhook: {
          create: vi.fn(),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "create_webhook",
      JSON.stringify({
        name: "Primary",
        url: "not-a-url",
        events: ["project.updated"],
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Webhook input is invalid.",
    });
    expect(ctx.db.webhook.create).not.toHaveBeenCalled();
  });

  it("returns a stable assistant error for invalid webhook update input", async () => {
    const ctx = createToolContext(
      {
        webhook: {
          findUnique: vi.fn().mockResolvedValue({
            id: "wh_1",
            name: "Primary",
            url: "https://example.com/hook",
            secret: null,
            events: ["project.updated"],
            isActive: true,
            createdAt: new Date("2026-03-29T00:00:00.000Z"),
            updatedAt: new Date("2026-03-29T00:00:00.000Z"),
          }),
          update: vi.fn(),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "update_webhook",
      JSON.stringify({
        id: "wh_1",
        data: {
          url: "not-a-url",
        },
      }),
      ctx,
    );

    expect(JSON.parse(result.content)).toEqual({
      error: "Webhook update input is invalid.",
    });
    expect(ctx.db.webhook.update).not.toHaveBeenCalled();
  });

  it("returns a stable assistant error when a webhook disappears during update", async () => {
    const ctx = createToolContext(
      {
        webhook: {
          findUnique: vi.fn().mockResolvedValue({
            id: "wh_1",
            name: "Primary",
            url: "https://example.com/hook",
            secret: null,
            events: ["project.updated"],
            isActive: true,
            createdAt: new Date("2026-03-29T00:00:00.000Z"),
            updatedAt: new Date("2026-03-29T00:00:00.000Z"),
          }),
          update: vi.fn().mockRejectedValue({
            code: "P2025",
            message: "Record to update not found.",
          }),
        },
      },
      { userRole: SystemRole.ADMIN },
    );

    const result = await executeTool(
      "update_webhook",
      JSON.stringify({
        id: "wh_1",
        data: {
          name: "Renamed",
        },
      }),
      ctx,
    );

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