import apiClient from './authApi';

export interface UserSummary {
  userId: string;
  email: string;
  displayName?: string;
  firstName?: string;
  lastName?: string;
  department?: string;
  phone?: string;
  mobilePhone?: string;
  designation?: string;
  jobTitle?: string;
  manager?: string;
  employeeId?: string;
  employeeNumber?: string;
  secondEmail?: string;
  location?: {
    state?: string;
    city?: string;
    country?: string;
    office?: string;
  };
  isActive?: boolean;
}

export async function searchUsers(query: string, limit: number = 10, source: 'local' | 'okta' | 'default' = 'default') {
  const res = await apiClient.get('/users/search', { params: { q: query, limit, source } });
  // ResponseHandler.success returns { success: true, data: array }
  return res;
}

/**
 * Ensure user exists in database (creates if not exists)
 * Call this when a user is selected/tagged to pre-create their record
 */
export async function ensureUserExists(userData: {
  userId: string;
  email: string;
  displayName?: string;
  firstName?: string;
  lastName?: string;
  department?: string;
  phone?: string;
  mobilePhone?: string;
  designation?: string;
  jobTitle?: string;
  manager?: string;
  employeeId?: string;
  employeeNumber?: string;
  secondEmail?: string;
  location?: {
    state?: string;
    city?: string;
    country?: string;
    office?: string;
  };
}): Promise<UserSummary> {
  const res = await apiClient.post('/users/ensure', userData);
  return (res.data?.data || res.data) as UserSummary;
}

/**
 * Assign role to user (creates user if doesn't exist)
 * @param email - User email
 * @param role - Role to assign
 */
export async function assignRole(
  email: string,
  role: 'USER' | 'MANAGEMENT' | 'ADMIN'
) {
  return await apiClient.post('/admin/users/assign-role', {
    email,
    role
  });
}

/**
 * Update user role by userId
 */
export async function updateUserRole(userId: string, role: 'USER' | 'MANAGEMENT' | 'ADMIN') {
  return await apiClient.put(`/admin/users/${userId}/role`, { role });
}

/**
 * Get users by role (with pagination)
 */
export async function getUsersByRole(
  role?: 'USER' | 'MANAGEMENT' | 'ADMIN' | 'ALL' | 'ELEVATED',
  page: number = 1,
  limit: number = 10
) {
  return await apiClient.get('/admin/users/by-role', {
    params: { role: role || 'ELEVATED', page, limit }
  });
}

/**
 * Get role statistics
 */
export async function getRoleStatistics() {
  return await apiClient.get('/admin/users/role-statistics');
}

/**
 * Get user by ID
 */
export async function getUserById(userId: string) {
  const res = await apiClient.get(`/users/${userId}`);
  return res.data?.data || res.data;
}

/**
 * Get all users from database (for filtering purposes)
 */
export async function getAllUsers() {
  const res = await apiClient.get('/users');
  // Response format: { success: true, data: { users: [...], total: number } }
  return res.data?.data?.users || [];
}

export const userApi = {
  searchUsers,
  getUserById,
  ensureUserExists,
  assignRole,
  updateUserRole,
  getUsersByRole,
  getRoleStatistics,
  getAllUsers
};

export default userApi;


