const router = require('express').Router()
const User = require('../models/user')
const virifyToken = require('../middlewares/verify-token')

const jwt = require('jsonwebtoken')

router.post('/auth/signup', async (req, res) => {
  if (!req.body.email || !req.body.password) {
    res.json({ success: false, message: 'please enter email or password' })
  } else {
    try {
      let newUser = new User()
      newUser.name = req.body.name
      newUser.email = req.body.email
      newUser.password =  req.body.password
      await newUser.save()

      let token =  jwt.sign(newUser.toJSON(), process.env.SECRET, {
        expiresIn: 604800
      })

      res.json({
        success: true,
        token,
        message: 'Succes created a new User'
      })
    } catch (err) {
      res.status(500).json({
        success: false,
        message: err.message
      })
    }
  }
})


router.get('/auth/user', virifyToken, async (req, res) => {
  try {
    let foundUser = await User.findOne({ _id: req.decoded._id })
    if (foundUser) {
      res.json({
        success: true,
        user: foundUser
      })
    }
  } catch (err) {
    res.status(500).json({
      success: false,
      message: err.message
    })
  }
})

module.exports = router