text: const router = require('express').Router()
  const { PrismaClient } = require('@prisma/client')
  const roles = require('@prisma/client').User_role
  const bcrypt = require('bcrypt')
  const prisma = new PrismaClient()
  const passport = require('passport')
  const authenticate = require('../middleware/passport')
  const { checkSchema, validationResult } = require('express-validator')
  
  router.post('/create', checkSchema({
      username: { in: ['body'], notEmpty: true, errorMessage: 'Username is not valid', isString: true, trim: true },
      password: { in: ['body'], notEmpty: true, errorMessage: 'Password is not valid', isString: true },
      personID: { in: ['body'], optional: true, errorMessage: 'Person ID is not valid', toInt: true, isInt: true },
      first_name: { in: ['body'], optional: true, errorMessage: 'First name not valid', trim: true, isString: true },
      last_name: { in: ['body'], optional: true, errorMessage: 'Last name not valid', trim: true, isString: true },
      depto: { in: ['body'], optional: true, errorMessage: 'Department name not valid', trim: true, isString: true },
  }), async (req, res, next) => {
      try {
          const errors = validationResult(req)
          if (!errors.isEmpty() || !(req.body.role in roles)) {
              res.status(422).json({ errors: errors.array() });
              return;
          } else {
              const { username } = req.body
  
              const userExists = await prisma.user.findOne({ where: { username } })
              if (userExists) {
                  res.send('Username is already being used')
              } else {
                  const { password, role, personID, first_name, last_name, depto } = req.body
                  const cryptPass = await bcrypt.hash(password, 12)
  
                  await prisma.user.create({
                      data: {
                          username,
                          password: cryptPass,
                          role,
                          person: {
                              connectOrCreate: {
                                  where: { ID: personID ? personID : -1 },
                                  create: {
                                      first_name: first_name ? first_name : undefined,
                                      last_name: last_name ? last_name : undefined,
                                      department: {
                                          connect: {
                                              name: depto ? depto : undefined
                                          }
                                      }
                                  }
                              }
                          }
                      },
                      select: { password: false, role: true, username: true, status: true, person: { select: { first_name: true, last_name: true, equipment: true } } }
                  })
                      .then(user => {
                          if (user) {
                              res.status(200).json({ message: 'User has been created', user })
                          } else {
                              res.status(500).json({ message: 'User could not be created' })
                          }
                      })
                      .catch(err => { res.status(500).json(err.message) })
              }
          }
      } catch (err) {
          res.status(500).send(err.message)
      }
  })
  
  router.get('/register', (req, res) => {
      res.send('register')
  })
  
  router.post('/login', passport.authenticate('local'), async (req, res, next) => {
      try {
          const token = authenticate.getToken({ username: req.user.username })
  
          if (token !== null) {
              const user = await prisma.user.findOne({
                  where: { username: req.user.username },
                  select: {
                      role: true,
                      person: {
                          select: {
                              equipment: { select: { IP: true } },
                              first_name: true, last_name: true
                          }
                      }
                  }
              })
  
              res.statusCode = 200;
              res.setHeader('Content-Type', 'application/json');
              res.json({ succes: true, token, user, status: 'Successfully logged in' });
          } else {
              res.statusCode = 400
              res.send('User does not exist')
          }
      } catch (err) {
          next(err)
      }
  })
  
  router.get('/logout', (req, res) => {
      req.logout();
      res.send('Loged Out')
      //res.redirect('/users/login');
  })
  
  router.get('/login', (req, res) => {
      res.send('login')
  })
  
  router.get('/all', authenticate.verifyUser, authenticate.verifyAB, async (req, res, next) => {
      try {
          const { role } = req.query
          await prisma.user.findMany({
              where: { role: role ? role : undefined },
              select: { password: false, role: true, username: true, status: true, person: { select: { first_name: true, last_name: true, equipment: true } } }
          })
              .then(users => {
                  if (users) {
                      res.status(200).json({ message: 'List of all existing users', users })
                  } else {
                      res.status(404).send('No users were found')
                  }
              })
              .catch(err => next(err))
      } catch (err) {
          next(err)
      }
  })
  
  router.get('/:username', authenticate.verifyUser, authenticate.verifyAB, checkSchema({
      username: { in: ['params'], notEmpty: true, errorMessage: 'Username is not valid', isString: true, trim: true },
  }), async (req, res, next) => {
      try {
          const errors = validationResult(req)
          if (!errors.isEmpty()) {
              res.status(422).json({ errors: errors.array() });
              return;
          } else {
              const { username } = req.params
              await prisma.user.findOne({ where: { username }, include: { person: { select: { first_name: true, last_name: true, equipment: true } } } })
                  .then(user => {
                      if (user) {
                          res.status(200).json({ message: `Result for user with username:${username}`, user })
                      } else {
                          res.status(404).json({ message: 'User was not found' })
                      }
                  })
                  .catch(next)
          }
      } catch (err) {
          res.status(500).send(err.message)
      }
  })
  
  router.put('/:username/update', authenticate.verifyUser, authenticate.verifyAdmin, checkSchema({
      username: { in: ['params'], notEmpty: true, errorMessage: 'Username is not valid', isString: true, trim: true },
      password: { in: ['body'], optional: true, errorMessage: 'Password is not valid', isString: true },
      role: { in: ['body'], optional: true, errorMessage: 'Role is not valid', isString: true, trim: true },
  }), async (req, res, next) => {
      try {
          const errors = validationResult(req)
          if (!errors.isEmpty()) {
              res.status(422).json({ errors: errors.array() });
              return;
          } else {
              const { username } = req.params
              const { password, role } = req.body
              const cryptPass = password ? await bcrypt.hash(password, 12) : undefined
              await prisma.user.update({
                  where: { username }, data: {
                      password: cryptPass ? cryptPass : undefined,
                      role: role !== null ? role : undefined,
                  },
                  select: { password: false, role: true, username: true, status: true, person: { select: { first_name: true, last_name: true, equipment: true } } }
              })
                  .then(user => {
                      res.status(200).json({ message: 'User has been updated', user })
                  })
                  .catch(err => next(err))
          }
      } catch (err) {
          res.status(500).send(err.message)
      }
  })
  
  // dismiss or activate user
  router.put('/:username/status', authenticate.verifyUser, authenticate.verifyAdmin, checkSchema({
      username: { in: ['params'], notEmpty: true, errorMessage: 'Username is not valid', isString: true, trim: true },
      status: { in: ['body'], notEmpty: true, errorMessage: 'Status is not valid', isBoolean: true, toBoolean: true },
  }), async (req, res, next) => {
      try {
          const errors = validationResult(req)
          if (!errors.isEmpty()) {
              res.status(422).json({ errors: errors.array() });
              return;
          } else {
              const { username } = req.params
              const { status } = req.body
              await prisma.user.update({
                  where: { username }, data: { status },
                  select: { password: false, role: true, username: true, status: true, person: { select: { first_name: true, last_name: true, equipment: true } } }
              })
                  .then(user => {
                      res.status(200).json({ message: `User has been ${status ? 'Activated' : 'Dismissed'}`, user: user.username })
                  })
                  .catch(err => next(err))
          }
      } catch (err) {
          res.status(500).send(err.message)
      }
  })
  
  // router.delete('/del/:username', checkSchema({
  //     username: { in: ['params'], notEmpty: true, errorMessage: 'Username is not valid', isString: true, trim: true },
  // }), authenticate.verifyUser, authenticate.verifyAdmin, async (req, res, next) => {
  //     try {
  //         const errors = validationResult(req)
  //         if (!errors.isEmpty()) {
  //             res.status(422).json({ errors: errors.array() });
  //             return;
  //         } else {
  //             const { username } = req.params
  //             await prisma.user.delete({ where: { username } })
  //                 .then(user => {
  //                     res.status(200).json({ message: 'User has been deleted', user: user.username })
  //                 })
  //                 .catch(err => next(err))
  //         }
  //     } catch (err) {
  //         res.status(500).send(err.message)
  //     }
  // })
  
  module.exports = router
  