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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_leads_list",
    description: "List all leads",
    inputSchema: {
      type: "object",
      properties: {
        limit: { type: "number" },
        start: { type: "number" },
        archived_status: { type: "string", description: "not_archived, archived, or all" },
        owner_id: { type: "number" },
        person_id: { type: "number" },
        organization_id: { type: "number" },
        filter_id: { type: "number" },
        sort: { type: "string" },
      },
    },
  },
  {
    name: "pipedrive_lead_get",
    description: "Get a single lead by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Lead ID (UUID)" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_lead_create",
    description: "Create a new lead",
    inputSchema: {
      type: "object",
      properties: {
        title: { type: "string", description: "Lead title" },
        owner_id: { type: "number", description: "Owner user ID" },
        person_id: { type: "number", description: "Associated person ID" },
        organization_id: { type: "number", description: "Associated organization ID" },
        value: { type: "string", description: "JSON object with amount and currency" },
        expected_close_date: { type: "string", description: "Expected close date (YYYY-MM-DD)" },
        visible_to: { type: "string", description: "Visibility: 1, 3, 5, 7" },
        label_ids: { type: "string", description: "Comma-separated label IDs" },
      },
      required: ["title"],
    },
  },
  {
    name: "pipedrive_lead_update",
    description: "Update an existing lead",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Lead ID (UUID)" },
        title: { type: "string" },
        owner_id: { type: "number" },
        person_id: { type: "number" },
        organization_id: { type: "number" },
        value: { type: "string", description: "JSON object with amount and currency" },
        expected_close_date: { type: "string" },
        label_ids: { type: "string", description: "Comma-separated label IDs" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_lead_delete",
    description: "Delete a lead",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Lead ID (UUID)" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_lead_labels_list",
    description: "List all lead labels",
    inputSchema: {
      type: "object",
      properties: {},
    },
  },
  {
    name: "pipedrive_lead_add_label",
    description: "Add a label to a lead",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "string", description: "Lead ID (UUID)" },
        label_id: { type: "string", description: "Label ID to add" },
      },
      required: ["id", "label_id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_leads_list": {
        const params: Record<string, unknown> = {};
        if (args.limit !== undefined) params.limit = args.limit;
        if (args.start !== undefined) params.start = args.start;
        if (args.archived_status) params.archived_status = args.archived_status;
        if (args.owner_id) params.owner_id = args.owner_id;
        if (args.person_id) params.person_id = args.person_id;
        if (args.organization_id) params.organization_id = args.organization_id;
        if (args.filter_id) params.filter_id = args.filter_id;
        if (args.sort) params.sort = args.sort;

        const result = await client.get<{ success: boolean; data: Lead[] }>("/leads", params);
        const leads = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${leads.length} leads\n${leads.map((l) => `- [${l.id}] ${l.title} (value: ${l.value?.amount || 0} ${l.value?.currency || ""})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_lead_get": {
        const result = await client.get<{ success: boolean; data: Lead }>(`/leads/${args.id}`);
        const lead = result.data;
        return {
          content: [{
            type: "text",
            text: `Lead: ${lead.title}\nID: ${lead.id}\nOwner ID: ${lead.owner_id || "N/A"}\nPerson ID: ${lead.person_id || "N/A"}\nOrg ID: ${lead.organization_id || "N/A"}\nValue: ${lead.value?.amount || 0} ${lead.value?.currency || ""}\nExpected close: ${lead.expected_close_date || "N/A"}`,
          }],
        };
      }

      case "pipedrive_lead_create": {
        const body: Record<string, unknown> = { ...args };
        if (args.value && typeof args.value === "string") {
          body.value = JSON.parse(args.value as string);
        }
        if (args.label_ids && typeof args.label_ids === "string") {
          body.label_ids = (args.label_ids as string).split(",");
        }
        const result = await client.post<{ success: boolean; data: Lead }>("/leads", body);
        const lead = result.data;
        return {
          content: [{ type: "text", text: `Created lead: ${lead.title} (ID: ${lead.id})` }],
        };
      }

      case "pipedrive_lead_update": {
        const { id, value, label_ids, ...updateData } = args;
        const body: Record<string, unknown> = { ...updateData };
        if (value && typeof value === "string") {
          body.value = JSON.parse(value as string);
        }
        if (label_ids && typeof label_ids === "string") {
          body.label_ids = (label_ids as string).split(",");
        }
        const result = await client.put<{ success: boolean; data: Lead }>(`/leads/${id}`, body);
        const lead = result.data;
        return {
          content: [{ type: "text", text: `Updated lead: ${lead.title} (ID: ${lead.id})` }],
        };
      }

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

      case "pipedrive_lead_labels_list": {
        const result = await client.get<{ success: boolean; data: Array<{ id: string; name: string; color: string }> }>("/leadLabels");
        const labels = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${labels.length} lead labels:\n${labels.map((l) => `- [${l.id}] ${l.name} (${l.color})`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_lead_add_label": {
        await client.post(`/leads/${args.id}/labels`, { label_id: args.label_id });
        return {
          content: [{ type: "text", text: `Added label ${args.label_id} to lead ${args.id}` }],
        };
      }

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