'use strict';
import { dbDelete, createDynamicSelect, dbInnerJoin, dbWhere, dbUpdate } from '../../db/db-connection.js';
import { getTableColumn, runQuery } from '../../db/drizzle-queries.js';
import { eq, and } from 'drizzle-orm';
import { getRoleByName } from '../auth/role-db.js';
import { singleOrUndefined } from '../../../fd-toolbox/server/collections/single-funcs.js';
import { userTokenPurposeConstants } from '../../common/users/user-token-purposes.js';
import { hash } from '@node-rs/argon2';
import { updateResource } from '../../meta/server/db/db.js';
import _0x58b317 from 'jsonwebtoken';
import { resourceNames } from '../../../fd-toolbox/resources/resource-names.js';
import { apiConflictError } from '../../../fd-toolbox/server/web/errors.js';
import { createError } from '../../../fd-toolbox/errors/errors.js';
import { metaErrorMessages } from '../../meta/constants/meta-error-messages-constants.js';
import { getUserDtosOrSingle, addRoleToUser } from './user-db.js';
import { userManagerMessages } from './user-manager-messages.js';
import { getDbSchema } from '../../db/db-schema.js';
import { schemaNames, columnNames } from '../../db/constants/schema-names.js';
import { userTokenConstants } from './user-token-constants.js';
import { wellKnownMetaProps } from '../../../fd-toolbox-core/constants/meta-constants.js';
import { commonLowerCaseWords } from '../../../base-repo/constants/internal-common-strings.js';

var __defProp=Object['defineProperty'],__name=(_0x4fae15,_0x5a96f8)=>__defProp(_0x4fae15,'name',{'value':_0x5a96f8,'configurable':!![]});const userSettings={'detail':commonLowerCaseWords['detail']};async function getUserRolesForPermission(_0x546cfe){const _0x59be2f=await getRolesAsync(_0x546cfe);if(_0x59be2f&&_0x59be2f['length']>-0x1*-0x827+0xb51+-0x1378)return _0x59be2f;else throw createError(metaErrorMessages['noRolesForUser']['replace']('{0}',_0x546cfe));}__name(getUserRolesForPermission,'getUserRolesForPermission');async function getUserDto(_0x11dba6){return singleOrUndefined(await getUserDtosOrSingle(_0x11dba6));}__name(getUserDto,'getUserDto');async function getUserDtos(){return getUserDtosOrSingle();}__name(getUserDtos,'getUserDtos');async function userManagerDeleteUser(_0x597199){const _0x3c452d=getDbSchema(),_0x1fb0a5=_0x3c452d[schemaNames['userSchema']];let _0x214adc;try{_0x214adc=await dbDelete(_0x1fb0a5)['where'](eq(getTableColumn(_0x1fb0a5,columnNames['id']),_0x597199))['returning']();}catch(_0x304ab7){if(_0x304ab7&&typeof _0x304ab7==='object'&&userSettings['detail']in _0x304ab7)throw apiConflictError(_0x304ab7['detail']?String(_0x304ab7['detail']):'');}return _0x214adc;}__name(userManagerDeleteUser,'userManagerDeleteUser');async function getRolesAsync(_0x326a95){const _0x3ab6d1=getDbSchema(),_0x340ba2=_0x3ab6d1[schemaNames['roleSchema']],_0x1a3f3a=_0x3ab6d1[schemaNames['userRoleSchema']],_0xabfecf=createDynamicSelect(_0x1a3f3a,{'name':getTableColumn(_0x340ba2,columnNames['name'])});dbInnerJoin(_0xabfecf,_0x340ba2,eq(getTableColumn(_0x1a3f3a,columnNames['roleId']),getTableColumn(_0x340ba2,columnNames['id']))),dbWhere(_0xabfecf,eq(getTableColumn(_0x1a3f3a,columnNames['userId']),_0x326a95));const _0x10a3f1=await runQuery(_0xabfecf);return _0x10a3f1['map'](_0x184916=>_0x184916['name']);}__name(getRolesAsync,'getRolesAsync');async function addToRole(_0x83537,_0xc66058){const _0x480cdf=await getRoleByName(_0xc66058);return addRoleToUser(_0x83537,_0x480cdf['id']);}__name(addToRole,'addToRole');function generatePasswordResetToken(_0x53a66f){return generateUserToken(_0x53a66f,userTokenPurposeConstants['resetPassword']);}__name(generatePasswordResetToken,'generatePasswordResetToken');async function resetPassword(_0x1e28a4,_0x39d109,_0x444e11){let _0x46fb34;if(!validateUserToken(_0x1e28a4,_0x39d109,userTokenPurposeConstants['resetPassword']))_0x46fb34={'isSuccess':![],'userFriendlyMessage':userManagerMessages['invalidToken']};else {_0x39d109['passwordHash']=await hash(_0x444e11,{'memoryCost':0x4c00,'timeCost':0x2,'outputLen':0x20,'parallelism':0x1});try{await updateResource(_0x39d109,resourceNames['user']),_0x46fb34={'isSuccess':!![],'userFriendlyMessage':userManagerMessages['passwordChanged']};}catch(_0xd3ebf3){_0x46fb34={'isSuccess':![],'userFriendlyMessage':_0xd3ebf3 instanceof Error?_0xd3ebf3['message']:metaErrorMessages['resetPasswordError']};}}return _0x46fb34;}__name(resetPassword,'resetPassword');async function updateUser(_0x30a789){const _0x1b4e24=getDbSchema(),_0x472176=_0x1b4e24[schemaNames['userSchema']],_0x4ccb18=await dbUpdate(_0x472176)['set'](_0x30a789)['where'](and(eq(getTableColumn(_0x472176,columnNames['id']),_0x30a789['id']),eq(getTableColumn(_0x472176,columnNames['passwordHash']),getTableColumn(_0x472176,columnNames['passwordHash']))))['returning']();return {'isSuccess':!!_0x4ccb18,'userFriendlyMessage':userManagerMessages['userUpdated']};}__name(updateUser,'updateUser');function generateUserToken(_0x24bffc,_0x39e321=''){const _0x30ef8a={'id':_0x24bffc['id'],'purpose':_0x39e321};return _0x58b317['sign'](_0x30ef8a,_0x24bffc['securityStamp'],{'algorithm':userTokenConstants['signingAlgorithm'],'expiresIn':'1d'});}__name(generateUserToken,'generateUserToken');function validateUserToken(_0x35e3f5,_0x181637,_0x28809a=''){try{const _0x258302=_0x58b317['verify'](_0x35e3f5,_0x181637['securityStamp'],{'algorithms':[userTokenConstants['signingAlgorithm']]});if(!hasTokenShape(_0x258302))return ![];if(typeof _0x258302['id']!=='string'||typeof _0x258302['purpose']!=='string')return ![];return _0x258302['id']===_0x181637['id']&&_0x258302['purpose']===_0x28809a;}catch{return ![];}}__name(validateUserToken,'validateUserToken');function hasTokenShape(_0x205a6d){return typeof _0x205a6d==='object'&&!!_0x205a6d&&wellKnownMetaProps['id']in _0x205a6d&&'purpose'in _0x205a6d;}__name(hasTokenShape,'hasTokenShape');

export { addToRole, generatePasswordResetToken, getRolesAsync, getUserDto, getUserDtos, getUserRolesForPermission, resetPassword, updateUser, userManagerDeleteUser };
