import { PipedriveClient, err } from "../client.js";
import type { ToolDefinition, ToolResult, Webhook } from "../types.js";

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_webhooks_list",
    description: "List all webhooks",
    inputSchema: {
      type: "object",
      properties: {},
    },
  },
  {
    name: "pipedrive_webhook_create",
    description: "Create a new webhook",
    inputSchema: {
      type: "object",
      properties: {
        subscription_url: { type: "string", description: "Webhook URL" },
        event_action: { type: "string", description: "added, updated, deleted, merged, *" },
        event_object: { type: "string", description: "deal, person, organization, product, user, pipeline, stage, activity, note, file, *" },
        user_id: { type: "number", description: "User ID to receive notifications" },
        http_auth_user: { type: "string", description: "HTTP basic auth username" },
        http_auth_password: { type: "string", description: "HTTP basic auth password" },
      },
      required: ["subscription_url", "event_action", "event_object"],
    },
  },
  {
    name: "pipedrive_webhook_delete",
    description: "Delete a webhook",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Webhook ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_webhooks_list": {
        const result = await client.get<{ success: boolean; data: Webhook[] }>("/webhooks");
        const webhooks = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${webhooks.length} webhooks:\n${webhooks.map((w) => `- [${w.id}] ${w.event_object}.${w.event_action} → ${w.subscription_url} (${w.is_active ? "active" : "inactive"})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_webhook_create": {
        const result = await client.post<{ success: boolean; data: Webhook }>("/webhooks", args);
        const webhook = result.data;
        return {
          content: [{ type: "text", text: `Created webhook: ${webhook.event_object}.${webhook.event_action} → ${webhook.subscription_url} (ID: ${webhook.id})` }],
        };
      }

      case "pipedrive_webhook_delete": {
        await client.delete(`/webhooks/${args.id}`);
        return {
          content: [{ type: "text", text: `Deleted webhook ${args.id}` }],
        };
      }

      default:
        return {
          content: [{ type: "text", text: `Unknown tool: ${name}` }],
          isError: true,
        };
    }
  } catch (error) {
    return err(error);
  }
}
