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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_goals_list",
    description: "List all goals",
    inputSchema: {
      type: "object",
      properties: {
        user_id: { type: "number", description: "Filter by user" },
        everyone: { type: "boolean", description: "Include company-wide goals" },
      },
    },
  },
  {
    name: "pipedrive_goal_get",
    description: "Get a single goal by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Goal ID (UUID)" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_goal_create",
    description: "Create a new goal",
    inputSchema: {
      type: "object",
      properties: {
        title: { type: "string", description: "Goal title" },
        assignee: { type: "string", description: "JSON assignee object (id, type)" },
        type: { type: "string", description: "JSON type object (name, params)" },
        expected_outcome: { type: "string", description: "JSON expected outcome (target, tracking_metric)" },
        duration: { type: "string", description: "JSON duration (start, end)" },
        interval: { type: "string", description: "weekly, monthly, quarterly, yearly" },
      },
      required: ["title", "type", "assignee", "expected_outcome", "duration", "interval"],
    },
  },
  {
    name: "pipedrive_goal_update",
    description: "Update an existing goal",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Goal ID (UUID)" },
        title: { type: "string" },
        expected_outcome: { type: "string", description: "JSON expected outcome" },
        is_active: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_goal_delete",
    description: "Delete a goal",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Goal ID (UUID)" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_goal_results",
    description: "Get results for a goal",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Goal ID (UUID)" },
      },
      required: ["id"],
    },
  },
];

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

        const result = await client.get<{ success: boolean; data: Goal[] }>("/goals", params);
        const goals = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${goals.length} goals:\n${goals.map((g) => `- [${g.id}] ${g.title} (${g.is_active ? "active" : "inactive"})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_goal_get": {
        const result = await client.get<{ success: boolean; data: Goal }>(`/goals/${args.id}`);
        const goal = result.data;
        return {
          content: [{
            type: "text",
            text: `Goal: ${goal.title}\nID: ${goal.id}\nType: ${goal.type.name}\nInterval: ${goal.interval}\nActive: ${goal.is_active ? "Yes" : "No"}\nTarget: ${goal.expected_outcome?.target || "N/A"}`,
          }],
        };
      }

      case "pipedrive_goal_create": {
        const body: Record<string, unknown> = { title: args.title, interval: args.interval };
        if (args.assignee && typeof args.assignee === "string") {
          body.assignee = JSON.parse(args.assignee as string);
        }
        if (args.type && typeof args.type === "string") {
          body.type = JSON.parse(args.type as string);
        }
        if (args.expected_outcome && typeof args.expected_outcome === "string") {
          body.expected_outcome = JSON.parse(args.expected_outcome as string);
        }
        if (args.duration && typeof args.duration === "string") {
          body.duration = JSON.parse(args.duration as string);
        }

        const result = await client.post<{ success: boolean; data: Goal }>("/goals", body);
        const goal = result.data;
        return {
          content: [{ type: "text", text: `Created goal: ${goal.title} (ID: ${goal.id})` }],
        };
      }

      case "pipedrive_goal_update": {
        const { id, expected_outcome, ...updateData } = args;
        const body: Record<string, unknown> = { ...updateData };
        if (expected_outcome && typeof expected_outcome === "string") {
          body.expected_outcome = JSON.parse(expected_outcome as string);
        }

        const result = await client.put<{ success: boolean; data: Goal }>(`/goals/${id}`, body);
        const goal = result.data;
        return {
          content: [{ type: "text", text: `Updated goal: ${goal.title} (ID: ${goal.id})` }],
        };
      }

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

      case "pipedrive_goal_results": {
        const result = await client.get<{ success: boolean; data: unknown }>(`/goals/${args.id}/results`);
        return {
          content: [{ type: "text", text: `Goal results:\n${JSON.stringify(result.data, null, 2)}` }],
        };
      }

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