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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_activities_list",
    description: "List all activities with optional filters",
    inputSchema: {
      type: "object",
      properties: {
        user_id: { type: "number" },
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        done: { type: "number", description: "0 or 1" },
        type: { type: "string", description: "Activity type" },
        start: { type: "number" },
        limit: { type: "number" },
      },
    },
  },
  {
    name: "pipedrive_activity_get",
    description: "Get a single activity by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Activity ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_activity_create",
    description: "Create a new activity",
    inputSchema: {
      type: "object",
      properties: {
        subject: { type: "string", description: "Activity subject" },
        type: { type: "string", description: "Activity type (call, meeting, task, etc.)" },
        due_date: { type: "string", description: "Due date (YYYY-MM-DD)" },
        due_time: { type: "string", description: "Due time (HH:MM)" },
        duration: { type: "string", description: "Duration (e.g., '01:00')" },
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        user_id: { type: "number", description: "Assigned user" },
        note: { type: "string" },
        done: { type: "number", description: "0 or 1" },
      },
      required: ["subject", "type"],
    },
  },
  {
    name: "pipedrive_activity_update",
    description: "Update an existing activity",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Activity ID" },
        subject: { type: "string" },
        due_date: { type: "string" },
        due_time: { type: "string" },
        duration: { type: "string" },
        done: { type: "number" },
        note: { type: "string" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_activity_delete",
    description: "Delete an activity",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Activity ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_activity_types_list",
    description: "List all activity types",
    inputSchema: {
      type: "object",
      properties: {},
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_activities_list": {
        const params: Record<string, unknown> = {};
        if (args.user_id) params.user_id = args.user_id;
        if (args.deal_id) params.deal_id = args.deal_id;
        if (args.person_id) params.person_id = args.person_id;
        if (args.org_id) params.org_id = args.org_id;
        if (args.done !== undefined) params.done = args.done;
        if (args.type) params.type = args.type;
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: Activity[] }>("/activities", params);
        const activities = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${activities.length} activities\n${activities.map((a) => `- [${a.id}] ${a.subject} (${a.type}, done: ${a.done ? "✓" : "✗"})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_activity_get": {
        const result = await client.get<{ success: boolean; data: Activity }>(`/activities/${args.id}`);
        const activity = result.data;
        return {
          content: [{
            type: "text",
            text: `Activity: ${activity.subject}\nID: ${activity.id}\nType: ${activity.type}\nDone: ${activity.done ? "Yes" : "No"}\nDue: ${activity.due_date || "N/A"} ${activity.due_time || ""}\nDeal ID: ${activity.deal_id || "N/A"}\nPerson ID: ${activity.person_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_activity_create": {
        const result = await client.post<{ success: boolean; data: Activity }>("/activities", args);
        const activity = result.data;
        return {
          content: [{ type: "text", text: `Created activity: ${activity.subject} (ID: ${activity.id})` }],
        };
      }

      case "pipedrive_activity_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: Activity }>(`/activities/${id}`, updateData);
        const activity = result.data;
        return {
          content: [{ type: "text", text: `Updated activity: ${activity.subject} (ID: ${activity.id})` }],
        };
      }

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

      case "pipedrive_activity_types_list": {
        const result = await client.get<{ success: boolean; data: ActivityType[] }>("/activityTypes");
        const types = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${types.length} activity types:\n${types.map((t) => `- ${t.name} (key: ${t.key_string})`).join("\n")}`,
          }],
        };
      }

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