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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_filters_list",
    description: "List all filters for a specific entity type",
    inputSchema: {
      type: "object",
      properties: {
        type: { type: "string", description: "deals, org, people, products, activities" },
      },
      required: ["type"],
    },
  },
  {
    name: "pipedrive_filter_get",
    description: "Get a single filter by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Filter ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_filter_create",
    description: "Create a new filter",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Filter name" },
        type: { type: "string", description: "deals, org, people, products, activities" },
        conditions: { type: "string", description: "JSON conditions object" },
        visible_to: { type: "string", description: "Visibility: 1, 3, 5, 7" },
      },
      required: ["name", "type"],
    },
  },
  {
    name: "pipedrive_filter_update",
    description: "Update an existing filter",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Filter ID" },
        name: { type: "string" },
        conditions: { type: "string", description: "JSON conditions object" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_filter_delete",
    description: "Delete a filter",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Filter ID" },
      },
      required: ["id"],
    },
  },
];

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

      case "pipedrive_filter_get": {
        const result = await client.get<{ success: boolean; data: Filter }>(`/filters/${args.id}`);
        const filter = result.data;
        return {
          content: [{
            type: "text",
            text: `Filter: ${filter.name}\nID: ${filter.id}\nType: ${filter.type}\nActive: ${filter.active_flag ? "Yes" : "No"}\nUser ID: ${filter.user_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_filter_create": {
        const body: Record<string, unknown> = { ...args };
        if (args.conditions && typeof args.conditions === "string") {
          body.conditions = JSON.parse(args.conditions as string);
        }
        const result = await client.post<{ success: boolean; data: Filter }>("/filters", body);
        const filter = result.data;
        return {
          content: [{ type: "text", text: `Created filter: ${filter.name} (ID: ${filter.id})` }],
        };
      }

      case "pipedrive_filter_update": {
        const { id, conditions, ...updateData } = args;
        const body: Record<string, unknown> = { ...updateData };
        if (conditions && typeof conditions === "string") {
          body.conditions = JSON.parse(conditions as string);
        }
        const result = await client.put<{ success: boolean; data: Filter }>(`/filters/${id}`, body);
        const filter = result.data;
        return {
          content: [{ type: "text", text: `Updated filter: ${filter.name} (ID: ${filter.id})` }],
        };
      }

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

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