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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_files_list",
    description: "List all files with optional filters",
    inputSchema: {
      type: "object",
      properties: {
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        product_id: { type: "number" },
        activity_id: { type: "number" },
        start: { type: "number" },
        limit: { type: "number" },
        sort: { type: "string" },
      },
    },
  },
  {
    name: "pipedrive_file_get",
    description: "Get a single file by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "File ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_file_create",
    description: "Upload a new file (requires file path or base64 data)",
    inputSchema: {
      type: "object",
      properties: {
        file: { type: "string", description: "File path or base64 data" },
        deal_id: { type: "number" },
        person_id: { type: "number" },
        org_id: { type: "number" },
        product_id: { type: "number" },
        activity_id: { type: "number" },
      },
      required: ["file"],
    },
  },
  {
    name: "pipedrive_file_update",
    description: "Update file details",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "File ID" },
        name: { type: "string", description: "File name" },
        description: { type: "string" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_file_delete",
    description: "Delete a file",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "File ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_file_download",
    description: "Get download URL for a file",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "File ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_files_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.product_id) params.product_id = args.product_id;
        if (args.activity_id) params.activity_id = args.activity_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: File[] }>("/files", params);
        const files = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${files.length} files\n${files.map((f) => `- [${f.id}] ${f.name} (${f.file_type}, ${f.file_size} bytes)`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_file_get": {
        const result = await client.get<{ success: boolean; data: File }>(`/files/${args.id}`);
        const file = result.data;
        return {
          content: [{
            type: "text",
            text: `File: ${file.name}\nID: ${file.id}\nType: ${file.file_type}\nSize: ${file.file_size} bytes\nURL: ${file.url || "N/A"}\nDeal ID: ${file.deal_id || "N/A"}\nPerson ID: ${file.person_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_file_create": {
        // Note: In production, this would handle actual file uploads
        // For now, we'll simulate the response
        return {
          content: [{ type: "text", text: "File upload requires multipart/form-data - use pipedrive_file_upload with actual file data" }],
          isError: true,
        };
      }

      case "pipedrive_file_update": {
        const { id, ...updateData } = args;
        const result = await client.put<{ success: boolean; data: File }>(`/files/${id}`, updateData);
        const file = result.data;
        return {
          content: [{ type: "text", text: `Updated file: ${file.name} (ID: ${file.id})` }],
        };
      }

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

      case "pipedrive_file_download": {
        const result = await client.get<{ success: boolean; data: File }>(`/files/${args.id}/download`);
        const file = result.data;
        return {
          content: [{ type: "text", text: `Download URL: ${file.url || "Not available"}` }],
        };
      }

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