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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_stages_list",
    description: "List all stages (optionally filtered by pipeline)",
    inputSchema: {
      type: "object",
      properties: {
        pipeline_id: { type: "number", description: "Filter by pipeline ID" },
      },
    },
  },
  {
    name: "pipedrive_stage_get",
    description: "Get a single stage by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Stage ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_stage_create",
    description: "Create a new stage",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "Stage name" },
        pipeline_id: { type: "number", description: "Pipeline ID" },
        deal_probability: { type: "number", description: "Deal probability (0-100)" },
        rotten_flag: { type: "boolean", description: "Enable rotting" },
        rotten_days: { type: "number", description: "Days until rotten" },
      },
      required: ["name", "pipeline_id"],
    },
  },
  {
    name: "pipedrive_stage_update",
    description: "Update an existing stage",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Stage ID" },
        name: { type: "string" },
        deal_probability: { type: "number" },
        rotten_flag: { type: "boolean" },
        rotten_days: { type: "number" },
        order_nr: { type: "number" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_stage_delete",
    description: "Delete a stage",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Stage ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_stage_deals",
    description: "Get deals in a stage",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Stage ID" },
        filter_id: { type: "number" },
        user_id: { type: "number" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_stages_list": {
        const params: Record<string, unknown> = {};
        if (args.pipeline_id) params.pipeline_id = args.pipeline_id;

        const result = await client.get<{ success: boolean; data: Stage[] }>("/stages", params);
        const stages = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${stages.length} stages:\n${stages.map((s) => `- [${s.id}] ${s.name} (pipeline ${s.pipeline_id}, probability: ${s.deal_probability}%)`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_stage_get": {
        const result = await client.get<{ success: boolean; data: Stage }>(`/stages/${args.id}`);
        const stage = result.data;
        return {
          content: [{
            type: "text",
            text: `Stage: ${stage.name}\nID: ${stage.id}\nPipeline ID: ${stage.pipeline_id}\nDeal probability: ${stage.deal_probability}%\nOrder: ${stage.order_nr}\nRotten: ${stage.rotten_flag ? `Yes (${stage.rotten_days} days)` : "No"}`,
          }],
        };
      }

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

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

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

      case "pipedrive_stage_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.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

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

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