text: const express = require('express')
  const { check, validationResult } = require('express-validator')
  const bcrypt = require('bcryptjs')
  const jwt = require('jsonwebtoken')
  const router = express.Router()
  
  const User = require('../../models/User')
  
  const TIME_TO_EXPIRE = 3600 //in seconds (1 hour)
  
  router.post("/",
    [
      check("email", "Please enter a valid email").isEmail(),
      check("password", "Please enter a valid password").isLength({
        min: 6
      })
    ],
    async (req, res) => {
      const errors = validationResult(req)
  
      if (!errors.isEmpty()) {
        return res.status(400).json({
          errors: errors.array()
        })
      }
      
      const { email, password } = req.body
      try {
        let user = await User.findOne({ email })
        if (!user) return res.status(400).json({ message: "Incorrect email / password" })
  
      const isMatch = await bcrypt.compare(password, user.password)
      if (!isMatch) return res.status(400).json({ message: "Incorrect email / password" })
        
        const payload = { user: { id: user.id } }
  
        jwt.sign(payload, "randomString", { expiresIn: TIME_TO_EXPIRE },
          (err, token) => {
            if (err) throw err
            res.status(200).json({ token })
          }
        )
      } catch (e) {
        console.error(e)
        res.status(500).json({
          message: "Server Error"
        })
      }
    }
  )
  
  module.exports = router
  