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

export const tools: ToolDefinition[] = [
  {
    name: "pipedrive_users_list",
    description: "List all users in the company",
    inputSchema: {
      type: "object",
      properties: {},
    },
  },
  {
    name: "pipedrive_user_get",
    description: "Get a single user by ID",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "User ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_user_create",
    description: "Add a new user (admin only)",
    inputSchema: {
      type: "object",
      properties: {
        name: { type: "string", description: "User name" },
        email: { type: "string", description: "User email" },
        active_flag: { type: "boolean", description: "Active flag" },
      },
      required: ["name", "email"],
    },
  },
  {
    name: "pipedrive_user_update",
    description: "Update an existing user",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "User ID" },
        name: { type: "string" },
        email: { type: "string" },
        active_flag: { type: "boolean" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_user_permissions",
    description: "Get user permissions",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "User ID" },
      },
      required: ["id"],
    },
  },
  {
    name: "pipedrive_user_role_assignments",
    description: "List user's role assignments",
    inputSchema: {
      type: "object",
      properties: {
        id: { type: "number", description: "User ID" },
      },
      required: ["id"],
    },
  },
];

export async function handle(
  client: PipedriveClient,
  name: string,
  args: Record<string, unknown>
): Promise<ToolResult> {
  try {
    switch (name) {
      case "pipedrive_users_list": {
        const result = await client.get<{ success: boolean; data: User[] }>("/users");
        const users = result.data || [];
        return {
          content: [{
            type: "text",
            text: `Found ${users.length} users:\n${users.map((u) => `- [${u.id}] ${u.name} (${u.email}) ${u.active_flag ? "✓" : "✗"}${u.is_admin ? " [admin]" : ""}`).join("\n")}`,
          }],
        };
      }

      case "pipedrive_user_get": {
        const result = await client.get<{ success: boolean; data: User }>(`/users/${args.id}`);
        const user = result.data;
        return {
          content: [{
            type: "text",
            text: `User: ${user.name}\nID: ${user.id}\nEmail: ${user.email}\nActive: ${user.active_flag ? "Yes" : "No"}\nAdmin: ${user.is_admin ? "Yes" : "No"}\nRole ID: ${user.role_id || "N/A"}`,
          }],
        };
      }

      case "pipedrive_user_create": {
        const result = await client.post<{ success: boolean; data: User }>("/users", args);
        const user = result.data;
        return {
          content: [{ type: "text", text: `Created user: ${user.name} (ID: ${user.id})` }],
        };
      }

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

      case "pipedrive_user_permissions": {
        const result = await client.get<{ success: boolean; data: unknown }>(`/users/${args.id}/permissions`);
        return {
          content: [{ type: "text", text: `User permissions:\n${JSON.stringify(result.data, null, 2)}` }],
        };
      }

      case "pipedrive_user_role_assignments": {
        const result = await client.get<{ success: boolean; data: unknown[] }>(`/users/${args.id}/roleAssignments`);
        const assignments = result.data || [];
        return {
          content: [{ type: "text", text: `Found ${assignments.length} role assignments for user ${args.id}` }],
        };
      }

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