const userRepository = require("../repositories/userRepository") const bcrypt = require("bcryptjs") const logger = require("../modules/logger") const { DefaultError } = require("../errors/errors") async function register({ firstName = null, lastName = null, username, password }) { const isUserExists = userRepository.findByUsername(username) if (isUserExists) { throw new DefaultError(409, "Username taken.") } try { const hashedPassword = await bcrypt.hash(password, 4) return userRepository.register(firstName, lastName, username, hashedPassword) } catch (error) { logger.error(error, ["Service", "yellow", "USER", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function remove(id) { const user = userRepository.findById(id) if (!user) { throw new DefaultError(404, "User not found.") } try { return userRepository.remove(id) } catch (error) { logger.error(error, ["Service", "yellow", "USER", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function changePassword(id, newPassword) { const user = userRepository.findById(id) if (!user) { throw new DefaultError(404, "User not found.") } try { const hashedPassword = await bcrypt.hash(newPassword, 4) return userRepository.changePassword(id, hashedPassword) } catch (error) { logger.error(error, ["Service", "yellow", "USER", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } function findById(id) { try { const user = userRepository.findById(id) if (!user) { throw new DefaultError(404, "User not found.") } return user } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "USER", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } module.exports = { remove, findById, register, changePassword, }