text: const { sendSuccess, sendError } = require('../helpers/send.helper');
  const bcrypt = require('bcrypt');
  const jwt = require('jsonwebtoken');
  const config = process.env;
  
  const saltRounds = 10;
  
  const {
  	sequelize,
  	User,
  	UserRole,
  	PermissionModule,
  } = require('../models');
  
  module.exports = {
  	login: async (req, res) => {
  		const { user, password } = req.body;
  		let resourcePermission = [];
  
  		try {
  			const userRow = await User.findOne({
  				where: { user, password, state: 1 }
  			});
  
  			if (!userRow) {
  				return res.status(404).json(
  					await sendError(
  						'Usuario o Contraseña Incorrecta.',
  						[],
  						404
  					));
  			} else {
  				// const validPassword = await bcrypt.compare(password, userRow.password);
  				/*
  				if (!validPassword) {
  					return res.status(404).json(
  						await sendError(
  							'Usuario o Contraseña Incorrecta.',
  							[],
  							404
  						));
  				}
  				*/
  			}
  
  			const userRoleRow = await UserRole.findOne({
  				where: { id: userRow.role_id }
  			});
  
  			const modulePermissions = await PermissionModule.findAll({
  				where: {
  					role_id: userRow.role_id
  				}
  			})
  
  			const keys = [...new Set(modulePermissions.map(item => item.module_id))];
  
  			keys.forEach(key => {
  				let permission = [...new Set(modulePermissions.filter(function (item) {
  					if (item.module_id == key) {
  						return item
  					}
  				}).map(e => e.permission_id))];
  
  				resourcePermission.push({
  					path: key,
  					permissions: permission
  				})
  
  			})
  
  			const accessToken = await jwt.sign(
  				{
  					user_id: userRow.id,
  					user
  				},
  				config.TOKEN_KEY
  			);
  
  			res.header('authorization', accessToken);
  
  			let login = {
  				'token': accessToken,
  				'token_type': 'Bearer',
  				'id': userRow.id,
  				'name': userRow.name,
  				'owner': userRow.owner,
  				'user': userRow.user,
  				'email': userRow.email,
  				'accepted': userRow.accepted,
  				resourcePermission
  			};
  
  
  			if (userRoleRow) {
  				login.role = {
  					id: userRoleRow.id,
  					name: userRoleRow.name
  				}
  			}
  
  			return res.status(200).json(
  				await sendSuccess(
  					'Inicio de Sesion.',
  					login,
  					[],
  					200
  				));
  		} catch (err) {
  			console.error('[ERROR] ', err);
  			return res.status(400).json(
  				await sendError(
  					'Algo ocurrio!',
  					err,
  					400
  				));
  		}
  	}
  }
  