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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_notes_list",
    description: "List all notes with optional filters",
    inputSchema: {
      type: "object",
      properties: {
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        lead_id: { type: "string" },
        start: { type: "number" },
        limit: { type: "number" },
        sort: { type: "string" },
      },
    },
  },
  {
    name: "pipedrive_note_get",
    description: "Get a single note by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Note ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_note_create",
    description: "Create a new note",
    inputSchema: {
      type: "object",
      properties: {
        content: { type: "string", description: "Note content" },
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        lead_id: { type: "string" },
        pinned_to_deal_flag: { type: "boolean" },
        pinned_to_person_flag: { type: "boolean" },
        pinned_to_organization_flag: { type: "boolean" },
        pinned_to_lead_flag: { type: "boolean" },
      },
      required: ["content"],
    },
  },
  {
    name: "pipedrive_note_update",
    description: "Update an existing note",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Note ID" },
        content: { type: "string" },
        pinned_to_deal_flag: { type: "boolean" },
        pinned_to_person_flag: { type: "boolean" },
        pinned_to_organization_flag: { type: "boolean" },
        pinned_to_lead_flag: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_note_delete",
    description: "Delete a note",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Note ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_notes_list": {
        const params: Record<string, unknown> = {};
        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.lead_id) params.lead_id = args.lead_id;
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;
        if (args.sort) params.sort = args.sort;

        const result = await client.get<{ success: boolean; data: Note[] }>("/notes", params);
        const notes = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${notes.length} notes\n${notes.map((n) => `- [${n.id}] ${n.content.substring(0, 60)}...`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_note_get": {
        const result = await client.get<{ success: boolean; data: Note }>(`/notes/${args.id}`);
        const note = result.data;
        return {
          content: [{
            type: "text",
            text: `Note ID: ${note.id}\nContent: ${note.content}\nDeal ID: ${note.deal_id || "N/A"}\nPerson ID: ${note.person_id || "N/A"}\nOrg ID: ${note.org_id || "N/A"}\nLead ID: ${note.lead_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_note_create": {
        const result = await client.post<{ success: boolean; data: Note }>("/notes", args);
        const note = result.data;
        return {
          content: [{ type: "text", text: `Created note (ID: ${note.id})` }],
        };
      }

      case "pipedrive_note_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: Note }>(`/notes/${id}`, updateData);
        const note = result.data;
        return {
          content: [{ type: "text", text: `Updated note (ID: ${note.id})` }],
        };
      }

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

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