/**
 * User, Role, and Profile management tools
 */

import type { SalesforceClient } from '../clients/salesforce.js';
import type { User, UserRole, Profile } from '../types/index.js';

export function getTools(client: SalesforceClient) {
  return [
    {
      name: 'sf_list_users',
      description: 'List users with optional filters. Returns up to 200 users by default.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of users to return (default: 200)',
            default: 200,
          },
          offset: {
            type: 'number',
            description: 'Number of records to skip (for pagination)',
          },
          isActive: {
            type: 'boolean',
            description: 'Filter by active status',
          },
        },
      },
      handler: async (args: { limit?: number; offset?: number; isActive?: boolean }) => {
        const conditions: string[] = [];
        if (args.isActive !== undefined) conditions.push(`IsActive = ${args.isActive}`);

        const soql = client.buildSOQL({
          select: ['Id', 'Username', 'Email', 'FirstName', 'LastName', 'Name', 'IsActive', 'Title', 'Department', 'UserRole.Name', 'Profile.Name', 'CreatedDate'],
          from: 'User',
          where: conditions.length > 0 ? conditions.join(' AND ') : undefined,
          orderBy: 'Name ASC',
          limit: args.limit || 200,
          offset: args.offset,
        });

        const result = await client.query<User>(soql);
        return {
          totalSize: result.totalSize,
          records: result.records,
          hasMore: !result.done,
        };
      },
    },

    {
      name: 'sf_get_user',
      description: 'Get detailed information about a specific user by ID',
      inputSchema: {
        type: 'object',
        properties: {
          userId: {
            type: 'string',
            description: 'The Salesforce ID of the user (15 or 18 characters)',
          },
        },
        required: ['userId'],
      },
      handler: async (args: { userId: string }) => {
        const user = await client.getRecord<User>('User', args.userId);
        return user;
      },
    },

    {
      name: 'sf_search_users',
      description: 'Search users by name, username, or email',
      inputSchema: {
        type: 'object',
        properties: {
          searchText: {
            type: 'string',
            description: 'Text to search in Name, Username, or Email fields',
          },
          isActive: {
            type: 'boolean',
            description: 'Filter by active status',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of results',
            default: 100,
          },
        },
      },
      handler: async (args: { searchText?: string; isActive?: boolean; limit?: number }) => {
        const conditions: string[] = [];
        
        if (args.searchText) {
          conditions.push(`(Name LIKE '%${args.searchText}%' OR Username LIKE '%${args.searchText}%' OR Email LIKE '%${args.searchText}%')`);
        }
        
        if (args.isActive !== undefined) {
          conditions.push(`IsActive = ${args.isActive}`);
        }

        const soql = client.buildSOQL({
          select: ['Id', 'Username', 'Email', 'FirstName', 'LastName', 'Name', 'IsActive', 'Title', 'Department', 'UserRole.Name', 'Profile.Name'],
          from: 'User',
          where: conditions.length > 0 ? conditions.join(' AND ') : undefined,
          orderBy: 'Name ASC',
          limit: args.limit || 100,
        });

        const result = await client.query<User>(soql);
        return result.records;
      },
    },

    {
      name: 'sf_list_roles',
      description: 'List user roles in the organization',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of roles to return',
            default: 200,
          },
        },
      },
      handler: async (args: { limit?: number }) => {
        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'DeveloperName', 'ParentRoleId'],
          from: 'UserRole',
          orderBy: 'Name ASC',
          limit: args.limit || 200,
        });

        const result = await client.query<UserRole>(soql);
        return result.records;
      },
    },

    {
      name: 'sf_get_role',
      description: 'Get detailed information about a specific user role',
      inputSchema: {
        type: 'object',
        properties: {
          roleId: {
            type: 'string',
            description: 'The Salesforce ID of the user role',
          },
        },
        required: ['roleId'],
      },
      handler: async (args: { roleId: string }) => {
        const role = await client.getRecord<UserRole>('UserRole', args.roleId);
        return role;
      },
    },

    {
      name: 'sf_list_profiles',
      description: 'List user profiles in the organization',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of profiles to return',
            default: 200,
          },
        },
      },
      handler: async (args: { limit?: number }) => {
        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'Description', 'UserType'],
          from: 'Profile',
          orderBy: 'Name ASC',
          limit: args.limit || 200,
        });

        const result = await client.query<Profile>(soql);
        return result.records;
      },
    },

    {
      name: 'sf_get_profile',
      description: 'Get detailed information about a specific profile',
      inputSchema: {
        type: 'object',
        properties: {
          profileId: {
            type: 'string',
            description: 'The Salesforce ID of the profile',
          },
        },
        required: ['profileId'],
      },
      handler: async (args: { profileId: string }) => {
        const profile = await client.getRecord<Profile>('Profile', args.profileId);
        return profile;
      },
    },

    {
      name: 'sf_get_user_permissions',
      description: 'Get permission sets assigned to a user',
      inputSchema: {
        type: 'object',
        properties: {
          userId: {
            type: 'string',
            description: 'The Salesforce ID of the user',
          },
        },
        required: ['userId'],
      },
      handler: async (args: { userId: string }) => {
        // Query PermissionSetAssignment
        const soql = client.buildSOQL({
          select: ['Id', 'PermissionSetId', 'PermissionSet.Name', 'PermissionSet.Label', 'AssigneeId'],
          from: 'PermissionSetAssignment',
          where: `AssigneeId = '${args.userId}'`,
          orderBy: 'PermissionSet.Name ASC',
        });

        const result = await client.query(soql);
        return result.records;
      },
    },
  ];
}
