// #region AdminService [C:3] [TYPE Service] [SEMANTICS admin, service, user, role, rbac]
// @BRIEF Service for Admin-related API calls including User and Role management, AD group mappings, and logging configuration.
// @LAYER Service
// @RELATION DEPENDS_ON -> [ApiModule]

// #region adminService:Module [TYPE Function]
//
// @SEMANTICS: admin, users, roles, ad-mappings, api
// @PURPOSE:   Service for Admin-related API calls (User and Role management).
// @LAYER     Service
// @RELATION  DEPENDS_ON -> [EXT:frontend:api_module]
//
// @INVARIANT: All requests must include valid Admin JWT token (handled by api client).

// [SECTION: IMPORTS]
import { api } from '../lib/api';
// [/SECTION]

interface UserData {
  username?: string;
  email?: string;
  password?: string;
  roles?: string[];
  is_active?: boolean;
  [key: string]: unknown;
}

interface RoleData {
  name?: string;
  description?: string;
  permissions?: string[];
  [key: string]: unknown;
}

interface ADGroupMappingData {
  ad_group?: string;
  role_id?: string;
  [key: string]: unknown;
}

interface LoggingConfigData {
  level?: string;
  task_log_level?: string;
  enable_belief_state?: boolean;
  [key: string]: unknown;
}

// #region getUsers:Function [TYPE Function]
/**
 * @purpose Fetches all registered users from the backend.
 * @pre     User must be authenticated with Admin privileges.
 * @post    Returns an array of user objects.
 * @returns Array of user objects.
 * @relation CALLS -> [EXT:path:backend.src.api.routes.admin.list_users]
 */
async function getUsers<T = unknown>(): Promise<T> {
    console.log('[getUsers][Entry]');
    try {
        const users = await api.requestApi<T>('/admin/users', 'GET');
        console.log('[getUsers][Coherence:OK]');
        return users;
    } catch (e) {
        console.error('[getUsers][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion getUsers:Function

// #region createUser:Function [TYPE Function]
/**
 * @purpose Creates a new local user.
 * @pre     User must be authenticated with Admin privileges.
 * @param   userData - User details (username, email, password, roles, is_active).
 * @post    New user record created in auth.db.
 * @returns New user object.
 * @relation CALLS -> [EXT:path:backend.src.api.routes.admin.create_user]
 */
async function createUser<T = unknown>(userData: UserData): Promise<T> {
    console.log('[createUser][Entry]');
    try {
        const user = await api.postApi<T>('/admin/users', userData);
        console.log('[createUser][Coherence:OK]');
        return user;
    } catch (e) {
        console.error('[createUser][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion createUser:Function

// #region getRoles:Function [TYPE Function]
/**
 * @purpose Fetches all available system roles.
 * @pre User must be authenticated with Admin privileges.
 * @post Returns an array of role objects.
 * @returns Array of role objects.
 * @relation CALLS -> [EXT:path:backend.src.api.routes.admin.list_roles]
 */
async function getRoles<T = unknown>(): Promise<T> {
    console.log('[getRoles][Entry]');
    try {
        const roles = await api.requestApi<T>('/admin/roles', 'GET');
        console.log('[getRoles][Coherence:OK]');
        return roles;
    } catch (e) {
        console.error('[getRoles][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion getRoles:Function

// #region getADGroupMappings:Function [TYPE Function]
/**
 * @purpose Fetches mappings between AD groups and local roles.
 * @pre User must be authenticated with Admin privileges.
 * @post Returns an array of AD group mapping objects.
 * @returns Array of AD group mapping objects.
 */
async function getADGroupMappings<T = unknown>(): Promise<T> {
    console.log('[getADGroupMappings][Entry]');
    try {
        const mappings = await api.requestApi<T>('/admin/ad-mappings', 'GET');
        console.log('[getADGroupMappings][Coherence:OK]');
        return mappings;
    } catch (e) {
        console.error('[getADGroupMappings][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion getADGroupMappings:Function

// #region createADGroupMapping:Function [TYPE Function]
/**
 * @purpose Creates or updates an AD group to Role mapping.
 * @pre User must be authenticated with Admin privileges.
 * @post New or updated mapping created in auth.db.
 * @param   mappingData - Mapping details (ad_group, role_id).
 * @returns New mapping object.
 */
async function createADGroupMapping<T = unknown>(mappingData: ADGroupMappingData): Promise<T> {
    console.log('[createADGroupMapping][Entry]');
    try {
        const mapping = await api.postApi<T>('/admin/ad-mappings', mappingData);
        console.log('[createADGroupMapping][Coherence:OK]');
        return mapping;
    } catch (e) {
        console.error('[createADGroupMapping][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion createADGroupMapping:Function

// #region updateUser:Function [TYPE Function]
/**
 * @purpose Updates an existing user.
 * @pre     User must be authenticated with Admin privileges.
 * @post    User record updated in auth.db.
 * @param   userId - Target user ID.
 * @param   userData - Updated user data.
 * @returns Updated user object.
 */
async function updateUser<T = unknown>(userId: string, userData: UserData): Promise<T> {
    console.log('[updateUser][Entry]');
    try {
        const user = await api.requestApi<T>(`/admin/users/${userId}`, 'PUT', userData);
        console.log('[updateUser][Coherence:OK]');
        return user;
    } catch (e) {
        console.error('[updateUser][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion updateUser:Function

// #region deleteUser:Function [TYPE Function]
/**
 * @purpose Deletes a user.
 * @pre     User must be authenticated with Admin privileges.
 * @post    User record removed from auth.db.
 * @param   userId - Target user ID.
 * @returns Promise that resolves when deletion is complete.
 */
async function deleteUser(userId: string): Promise<void> {
    console.log('[deleteUser][Entry]');
    try {
        await api.requestApi(`/admin/users/${userId}`, 'DELETE');
        console.log('[deleteUser][Coherence:OK]');
    } catch (e) {
        console.error('[deleteUser][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion deleteUser:Function

// #region createRole:Function [TYPE Function]
/**
 * @purpose Creates a new role.
 * @pre     User must be authenticated with Admin privileges.
 * @post    New role created in auth.db.
 * @param   roleData - Role details (name, description, permissions).
 * @returns New role object.
 */
async function createRole<T = unknown>(roleData: RoleData): Promise<T> {
    console.log('[createRole][Entry]');
    try {
        const role = await api.postApi<T>('/admin/roles', roleData);
        console.log('[createRole][Coherence:OK]');
        return role;
    } catch (e) {
        console.error('[createRole][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion createRole:Function

// #region updateRole:Function [TYPE Function]
/**
 * @purpose Updates an existing role.
 * @param   roleId - Target role ID.
 * @param   roleData - Updated role data.
 * @returns Updated role object.
 */
async function updateRole<T = unknown>(roleId: string, roleData: RoleData): Promise<T> {
    console.log('[updateRole][Entry]');
    try {
        const role = await api.requestApi<T>(`/admin/roles/${roleId}`, 'PUT', roleData);
        console.log('[updateRole][Coherence:OK]');
        return role;
    } catch (e) {
        console.error('[updateRole][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion updateRole:Function

// #region deleteRole:Function [TYPE Function]
/**
 * @purpose Deletes a role.
 * @param   roleId - Target role ID.
 * @returns Promise that resolves when deletion is complete.
 */
async function deleteRole(roleId: string): Promise<void> {
    console.log('[deleteRole][Entry]');
    try {
        await api.requestApi(`/admin/roles/${roleId}`, 'DELETE');
        console.log('[deleteRole][Coherence:OK]');
    } catch (e) {
        console.error('[deleteRole][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion deleteRole:Function

// #region getPermissions:Function [TYPE Function]
/**
 * @purpose Fetches all available permissions.
 * @returns Array of permission objects.
 */
async function getPermissions<T = unknown>(): Promise<T> {
    console.log('[getPermissions][Entry]');
    try {
        const permissions = await api.requestApi<T>('/admin/permissions', 'GET');
        console.log('[getPermissions][Coherence:OK]');
        return permissions;
    } catch (e) {
        console.error('[getPermissions][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion getPermissions:Function

// #region getLoggingConfig:Function [TYPE Function]
/**
 * @purpose Fetches current logging configuration.
 * @returns Logging config with level, task_log_level, enable_belief_state.
 * @relation CALLS -> [EXT:path:backend.src.api.routes.settings.get_logging_config]
 */
async function getLoggingConfig<T = unknown>(): Promise<T> {
    console.log('[getLoggingConfig][Entry]');
    try {
        const config = await api.requestApi<T>('/settings/logging', 'GET');
        console.log('[getLoggingConfig][Coherence:OK]');
        return config;
    } catch (e) {
        console.error('[getLoggingConfig][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion getLoggingConfig:Function

// #region updateLoggingConfig:Function [TYPE Function]
/**
 * @purpose Updates logging configuration.
 * @param   configData - Logging config (level, task_log_level, enable_belief_state).
 * @returns Updated logging config.
 * @relation CALLS -> [EXT:path:backend.src.api.routes.settings.update_logging_config]
 */
async function updateLoggingConfig<T = unknown>(configData: LoggingConfigData): Promise<T> {
    console.log('[updateLoggingConfig][Entry]');
    try {
        const config = await api.requestApi<T>('/settings/logging', 'PATCH', configData);
        console.log('[updateLoggingConfig][Coherence:OK]');
        return config;
    } catch (e) {
        console.error('[updateLoggingConfig][Coherence:Failed]', e);
        throw e;
    }
}
// #endregion updateLoggingConfig:Function

export const adminService = {
    getUsers,
    createUser,
    updateUser,
    deleteUser,
    getRoles,
    createRole,
    updateRole,
    deleteRole,
    getPermissions,
    getADGroupMappings,
    createADGroupMapping,
    getLoggingConfig,
    updateLoggingConfig
};

// #endregion adminService:Module
// #endregion AdminService
