const permissionsRepository = require("../repositories/permissionsRepository") const userRepository = require("../repositories/userRepository") const logger = require("../modules/logger") const { DefaultError } = require("../errors/errors") async function grant({ userId, productId, channel, permissionKey }) { const user = userRepository.findById(userId) if (!user) { throw new DefaultError(404, "User not found.") } try { return permissionsRepository.grant(userId, productId, channel, permissionKey) } catch (error) { logger.error(error, ["Service", "yellow", "PERMISSION", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function revoke({ userId, productId, channel, permissionKey }) { try { const result = permissionsRepository.revoke(userId, productId, channel, permissionKey) if (result.changes === 0) { throw new DefaultError(404, "Permission not found or already revoked.") } return result } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "PERMISSION", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } function findByUserAndProduct(userId, productId) { try { const permissions = permissionsRepository.findByUserAndProduct(userId, productId) if (!permissions || permissions.length === 0) { throw new DefaultError(404, "No permissions found for this user and product.") } return permissions } catch (error) { if (error instanceof DefaultError) throw error logger.error(error, ["Service", "yellow", "PERMISSION", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } async function revokeAllOnProduct(userId, productId) { try { return permissionsRepository.revokeAllOnProduct(userId, productId) } catch (error) { logger.error(error, ["Service", "yellow", "PERMISSION", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } function checkPermission(userId, productName, channel, permission) { try { return permissionsRepository.hasPermission(userId, productName, channel, permission) } catch (error) { logger.error(error, ["Service", "yellow", "PERMISSION", "green"]) throw new DefaultError(500, "Please contact the maintainer") } } module.exports = { grant, revoke, checkPermission, revokeAllOnProduct, findByUserAndProduct }