/**
 * User management API client.
 * 
 * Provides functions to manage users (CRUD operations).
 * Access is role-based: admin can manage user/editor/admin, superadmin can manage all.
 */

export interface UserData {
  id: number;
  username: string;
  role: 'user' | 'editor' | 'admin' | 'superadmin';
  isActive: boolean;
  lastLoginAt?: string;
  lastPasswordChangeAt?: string;
  lastFailedLoginAt?: string;
  failedLoginAttempts?: number;
  lockedUntil?: string;
  deactivatedAt?: string;
  createdAt?: string;
  updatedAt?: string;
}

export interface CreateUserRequest {
  username: string;
  password: string;
  role: 'user' | 'editor' | 'admin' | 'superadmin';
  isActive?: boolean;
}

export interface UpdateUserRequest {
  username?: string;
  role?: 'user' | 'editor' | 'admin' | 'superadmin';
  isActive?: boolean;
}

export interface ResetPasswordRequest {
  password: string;
}

/**
 * List all users (filtered by current user's role).
 * Admin sees: user, editor, admin
 * Superadmin sees: all including superadmin
 */
export async function listUsers(): Promise<UserData[]> {
  const res = await fetch('/api/users', {
    method: 'GET',
    credentials: 'include',
  });
  
  if (!res.ok) {
    const data = await res.json();
    throw new Error(data.error || 'Failed to fetch users');
  }
  
  return res.json();
}

/**
 * Get a single user by ID.
 */
export async function getUser(userId: number): Promise<UserData> {
  const res = await fetch(`/api/users/${userId}`, {
    method: 'GET',
    credentials: 'include',
  });
  
  if (!res.ok) {
    const data = await res.json();
    throw new Error(data.error || 'Failed to fetch user');
  }
  
  return res.json();
}

/**
 * Create a new user.
 * Admin: can create user, editor, admin
 * Superadmin: can create any role including superadmin
 */
export async function createUser(userData: CreateUserRequest): Promise<UserData & { message: string }> {
  const res = await fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify(userData),
  });
  
  const data = await res.json();
  
  if (!res.ok) {
    throw new Error(data.error || 'Failed to create user');
  }
  
  return data;
}

/**
 * Update a user's details.
 * Restrictions:
 * - Cannot change own role
 * - Cannot change own active status
 * - Admin cannot edit superadmin users
 */
export async function updateUser(userId: number, userData: UpdateUserRequest): Promise<UserData & { message: string }> {
  const res = await fetch(`/api/users/${userId}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify(userData),
  });
  
  const data = await res.json();
  
  if (!res.ok) {
    throw new Error(data.error || 'Failed to update user');
  }
  
  return data;
}

/**
 * Reset a user's password.
 * Admin: cannot reset superadmin passwords
 * Superadmin: can reset any password
 */
export async function resetUserPassword(userId: number, password: string): Promise<{ message: string }> {
  const res = await fetch(`/api/users/${userId}/password`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'include',
    body: JSON.stringify({ password }),
  });
  
  const data = await res.json();
  
  if (!res.ok) {
    throw new Error(data.error || 'Failed to reset password');
  }
  
  return data;
}

/**
 * Permanently delete a user (superadmin only).
 * Cannot delete own account.
 */
export async function deleteUser(userId: number): Promise<{ message: string }> {
  const res = await fetch(`/api/users/${userId}`, {
    method: 'DELETE',
    credentials: 'include',
  });
  
  const data = await res.json();
  
  if (!res.ok) {
    throw new Error(data.error || 'Failed to delete user');
  }
  
  return data;
}
