import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { listRoles } from '../../services/roles.service.js'
import { UserType } from '../../constants.js'

const attachCcUser = async (request, reply) => {
  if (request.auth?.userType !== UserType.CC_USER) {
    return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  }
  const user = await getCcUserById(request.auth.userId)
  if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
  request.ccUser = user
}

export const rolesRoutes = async (app) => {
  app.get('/', {
    preHandler: [authenticate, attachCcUser, requirePermission('control_center_users', 'read')],
  }, async (request, reply) => {
    const roles = await listRoles()
    return reply.send({ success: true, data: roles })
  })
}
