const express = require('express')
const router = express.Router()
const connection = require('../bdconnect')
const mysql = require('mysql')
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt-nodejs')
const cors = require('cors')
const nodeMailer = require('nodemailer')
require('dotenv').config()

router.use(cors())

var SECRET_KEY = process.env.SECRET_KEY
// var checkToken = require('./checkToken')

// CREATE NEW USER
// router.post('/', checkToken, (req, res) => {
router.post('/', (req, res) => {
    jwt.verify(req.token, SECRET_KEY, (err, results) => {
        var encPassword = bcrypt.hashSync(req.body.password)
        if (err) {
            //If error send Forbidden (403)
            res.sendStatus(403)
        } else {
            connection.query(
                'INSERT INTO users (username, name, last_name, password, role, avatar, email)',
                [
                    req.body.username,
                    req.body.name,
                    req.body.last_name,
                    encPassword,
                    1,
                    req.body.avatar,
                    req.body.email,
                ],
                function (error, results, fields) {
                    if (error) throw error
                    res.send(results)
                }
            )
        }
    })
})

module.exports = router