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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_pipelines_list",
    description: "List all pipelines",
    inputSchema: {
      type: "object",
      properties: {},
    },
  },
  {
    name: "pipedrive_pipeline_get",
    description: "Get a single pipeline by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_pipeline_create",
    description: "Create a new pipeline",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Pipeline name" },
        deal_probability: { type: "boolean", description: "Enable deal probability" },
        order_nr: { type: "number", description: "Order number" },
        active: { type: "boolean", description: "Active flag" },
      },
      required: ["name"],
    },
  },
  {
    name: "pipedrive_pipeline_update",
    description: "Update an existing pipeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
        name: { type: "string" },
        deal_probability: { type: "boolean" },
        order_nr: { type: "number" },
        active: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_pipeline_delete",
    description: "Delete a pipeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_pipeline_deals",
    description: "Get deals in a pipeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
        filter_id: { type: "number" },
        user_id: { type: "number" },
        stage_id: { type: "number" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_pipeline_statistics",
    description: "Get conversion statistics for a pipeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
        start_date: { type: "string", description: "Start date (YYYY-MM-DD)" },
        end_date: { type: "string", description: "End date (YYYY-MM-DD)" },
        user_id: { type: "number" },
      },
      required: ["id", "start_date", "end_date"],
    },
  },
  {
    name: "pipedrive_pipeline_movement_statistics",
    description: "Get movement statistics for a pipeline (deals moved between stages)",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
        start_date: { type: "string", description: "Start date (YYYY-MM-DD)" },
        end_date: { type: "string", description: "End date (YYYY-MM-DD)" },
        user_id: { type: "number" },
      },
      required: ["id", "start_date", "end_date"],
    },
  },
  {
    name: "pipedrive_pipeline_stages",
    description: "List all stages in a pipeline",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Pipeline ID" },
      },
      required: ["id"],
    },
  },
];

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

      case "pipedrive_pipeline_get": {
        const result = await client.get<{ success: boolean; data: Pipeline }>(`/pipelines/${args.id}`);
        const pipeline = result.data;
        return {
          content: [{
            type: "text",
            text: `Pipeline: ${pipeline.name}\nID: ${pipeline.id}\nActive: ${pipeline.active}\nDeal probability: ${pipeline.deal_probability}\nOrder: ${pipeline.order_nr}`,
          }],
        };
      }

      case "pipedrive_pipeline_create": {
        const result = await client.post<{ success: boolean; data: Pipeline }>("/pipelines", args);
        const pipeline = result.data;
        return {
          content: [{ type: "text", text: `Created pipeline: ${pipeline.name} (ID: ${pipeline.id})` }],
        };
      }

      case "pipedrive_pipeline_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: Pipeline }>(`/pipelines/${id}`, updateData);
        const pipeline = result.data;
        return {
          content: [{ type: "text", text: `Updated pipeline: ${pipeline.name} (ID: ${pipeline.id})` }],
        };
      }

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

      case "pipedrive_pipeline_deals": {
        const params: Record<string, unknown> = {};
        if (args.filter_id) params.filter_id = args.filter_id;
        if (args.user_id) params.user_id = args.user_id;
        if (args.stage_id) params.stage_id = args.stage_id;
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: unknown[] }>(`/pipelines/${args.id}/deals`, params);
        const deals = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${deals.length} deals in pipeline ${args.id}` }],
        };
      }

      case "pipedrive_pipeline_statistics": {
        const params: Record<string, unknown> = {
          start_date: args.start_date,
          end_date: args.end_date,
        };
        if (args.user_id) params.user_id = args.user_id;

        const result = await client.get<{ success: boolean; data: unknown }>(`/pipelines/${args.id}/conversion_statistics`, params);
        return {
          content: [{ type: "text", text: `Pipeline statistics:\n${JSON.stringify(result.data, null, 2)}` }],
        };
      }

      case "pipedrive_pipeline_movement_statistics": {
        const params: Record<string, unknown> = {
          start_date: args.start_date,
          end_date: args.end_date,
        };
        if (args.user_id) params.user_id = args.user_id;

        const result = await client.get<{ success: boolean; data: unknown }>(`/pipelines/${args.id}/movement_statistics`, params);
        return {
          content: [{ type: "text", text: `Pipeline movement statistics:\n${JSON.stringify(result.data, null, 2)}` }],
        };
      }

      case "pipedrive_pipeline_stages": {
        const result = await client.get<{ success: boolean; data: unknown[] }>(`/pipelines/${args.id}/stages`);
        const stages = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${stages.length} stages in pipeline ${args.id}` }],
        };
      }

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