/**
 * Database MCP Server - Users
 *
 * Provides user management operations for Prisma database.
 * Token savings: 10,000+ per operation (large user datasets, auth flows)
 */

import { callMCPTool } from "../../client.js";

export interface User {
  id: string;
  email: string;
  name: string | null;
  companyName: string | null;
  phone: string | null;
  industry: string | null;
  location: string | null;
  emailVerified: Date | null;
  createdAt: Date;
  failedLoginAttempts: number;
  lockoutUntil: Date | null;
}

export interface GetUsersInput {
  limit?: number;
  offset?: number;
  emailVerified?: boolean;
  industry?: string;
  location?: string;
}

export interface CreateUserInput {
  email: string;
  password: string;
  name?: string;
  companyName?: string;
  phone?: string;
  industry?: string;
  location?: string;
}

export interface UpdateUserInput {
  name?: string;
  companyName?: string;
  phone?: string;
  industry?: string;
  location?: string;
}

export interface UserStats {
  total: number;
  verified: number;
  unverified: number;
  locked: number;
  byIndustry: Record<string, number>;
  byLocation: Record<string, number>;
}

/**
 * Get users from the database with optional filtering.
 *
 * @param input - Query parameters
 * @returns Array of user objects (password excluded)
 *
 * @example
 * ```typescript
 * // Get verified users
 * const verified = await getUsers({ emailVerified: true, limit: 50 });
 *
 * // Get users by industry
 * const healthcare = await getUsers({ industry: 'healthcare' });
 *
 * // Process in code
 * const byLocation = healthcare.reduce((acc, u) => {
 *   const loc = u.location || 'Unknown';
 *   acc[loc] = (acc[loc] || 0) + 1;
 *   return acc;
 * }, {});
 * console.log('Users by location:', byLocation);
 * ```
 */
export async function getUsers(input: GetUsersInput = {}): Promise<User[]> {
  return callMCPTool<User[]>("database__get_users", input);
}

/**
 * Get a single user by email.
 *
 * @param email - User email address
 * @returns User object or null
 *
 * @example
 * ```typescript
 * const user = await getUserByEmail('user@example.com');
 * if (user) {
 *   console.log(`User: ${user.name} (${user.companyName})`);
 *   console.log(`Verified: ${user.emailVerified ? 'Yes' : 'No'}`);
 * }
 * ```
 */
export async function getUserByEmail(email: string): Promise<User | null> {
  return callMCPTool<User | null>("database__get_user_by_email", { email });
}

/**
 * Get user statistics and aggregations.
 *
 * @returns User stats including counts by industry and location
 *
 * @example
 * ```typescript
 * const stats = await getUserStats();
 * console.log(`Total: ${stats.total}, Verified: ${stats.verified}`);
 * console.log('Top industries:', Object.entries(stats.byIndustry).slice(0, 5));
 * ```
 */
export async function getUserStats(): Promise<UserStats> {
  return callMCPTool<UserStats>("database__get_user_stats", {});
}

/**
 * Create a new user (for programmatic user creation).
 *
 * @param input - User creation data
 * @returns Created user object
 *
 * @example
 * ```typescript
 * const newUser = await createUser({
 *   email: 'new@example.com',
 *   password: 'SecurePass123!',
 *   name: 'John Doe',
 *   companyName: 'Acme Corp',
 *   industry: 'healthcare'
 * });
 * console.log(`User created: ${newUser.id}`);
 * ```
 */
export async function createUser(input: CreateUserInput): Promise<User> {
  return callMCPTool<User>("database__create_user", input);
}

/**
 * Update user profile information.
 *
 * @param userId - User ID
 * @param input - Fields to update
 * @returns Updated user object
 *
 * @example
 * ```typescript
 * const updated = await updateUser('user_123', {
 *   companyName: 'New Company Name',
 *   phone: '+966501234567'
 * });
 * console.log('User updated:', updated.companyName);
 * ```
 */
export async function updateUser(
  userId: string,
  input: UpdateUserInput,
): Promise<User> {
  return callMCPTool<User>("database__update_user", { userId, ...input });
}

/**
 * Delete a user (soft delete - marks as deleted).
 *
 * @param userId - User ID to delete
 * @returns Success confirmation
 *
 * @example
 * ```typescript
 * await deleteUser('user_123');
 * console.log('User deleted successfully');
 * ```
 */
export async function deleteUser(
  userId: string,
): Promise<{ success: boolean }> {
  return callMCPTool<{ success: boolean }>("database__delete_user", { userId });
}

export default {
  getUsers,
  getUserByEmail,
  getUserStats,
  createUser,
  updateUser,
  deleteUser,
};
