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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_mail_threads_list",
    description: "List mail threads",
    inputSchema: {
      type: "object",
      properties: {
        folder: { type: "string", description: "inbox, drafts, sent, archive" },
        start: { type: "number" },
        limit: { type: "number" },
      },
      required: ["folder"],
    },
  },
  {
    name: "pipedrive_mail_thread_get",
    description: "Get a single mail thread by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Mail thread ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_mail_messages_list",
    description: "List messages in a thread",
    inputSchema: {
      type: "object",
      properties: {
        thread_id: { type: "number", description: "Mail thread ID" },
      },
      required: ["thread_id"],
    },
  },
  {
    name: "pipedrive_mail_message_get",
    description: "Get a single mail message by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Mail message ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_mail_message_delete",
    description: "Delete a mail message",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "Mail message ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_mail_threads_list": {
        const params: Record<string, unknown> = { folder: args.folder };
        if (args.start !== undefined) params.start = args.start;
        if (args.limit !== undefined) params.limit = args.limit;

        const result = await client.get<{ success: boolean; data: MailThread[] }>("/mailbox/mailThreads", params);
        const threads = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${threads.length} mail threads in ${args.folder}:\n${threads.map((t) => `- [${t.id}] ${t.subject || "(no subject)"} ${t.read_flag ? "" : "🔵"}`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_mail_thread_get": {
        const result = await client.get<{ success: boolean; data: MailThread }>(`/mailbox/mailThreads/${args.id}`);
        const thread = result.data;
        return {
          content: [{
            type: "text",
            text: `Thread: ${thread.subject || "(no subject)"}\nID: ${thread.id}\nSnippet: ${thread.snippet || "N/A"}\nRead: ${thread.read_flag ? "Yes" : "No"}\nDeal ID: ${thread.deal_id || "N/A"}\nLead ID: ${thread.lead_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_mail_messages_list": {
        const result = await client.get<{ success: boolean; data: MailMessage[] }>(`/mailbox/mailThreads/${args.thread_id}/mailMessages`);
        const messages = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${messages.length} messages in thread ${args.thread_id}:\n${messages.map((m) => `- [${m.id}] From: ${m.from[0]?.email_address || "unknown"} - ${m.subject || "(no subject)"}`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_mail_message_get": {
        const result = await client.get<{ success: boolean; data: MailMessage }>(`/mailbox/mailMessages/${args.id}`);
        const message = result.data;
        return {
          content: [{
            type: "text",
            text: `Message: ${message.subject || "(no subject)"}\nID: ${message.id}\nFrom: ${message.from[0]?.email_address || "unknown"}\nTo: ${message.to.map((t) => t.email_address).join(", ")}\nSnippet: ${message.snippet || "N/A"}\nBody URL: ${message.body_url}`,
          }],
        };
      }

      case "pipedrive_mail_message_delete": {
        await client.delete(`/mailbox/mailMessages/${args.id}`);
        return {
          content: [{ type: "text", text: `Deleted mail message ${args.id}` }],
        };
      }

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