import express from 'express'
import User from '../models/user'

const users = express.Router()

users.get('/', async (req, res) => {
    try {
      const users = await User.find()
      return res.json(users)
    } catch (error) {
      return res.status(400).json({ msg: error.toString() })
    }
})

users.get('/:username', (req, res) => {
    const { username } = req.params

    if (!username) {
        res.status(400).json({
            msg: 'Parameter username is required'
        })
        return
    }

    const dbUser = User.findOne({ username }).lean()
    dbUser.exec((err, user) => {
        if (err) {
            res.status(400).json({
                msg: err.toString()
            })
            return
        }

        return res.json({
            user: JSON.stringify(user)
        })
    })
})

users.post('/', (req, res) => {
  const { username, name, password } = req.body

  // return, if username or password are missing
  if (!username || !name || !password) {
    res.status(400).json({
      msg: 'Parameters username, name and password are required'
    })
    return
  }
  const user = new User({
      username,
      name,
      password
  })
  user.save((err) => {
      if (err) {
        res.status(400).json({
            msg: err.toString()
        })
        return
      }
      res.json({
        user_id: user._id
      })
  })
}) 

users.put('/', (req, res) => {
    const { username, name, password } = req.body

    // return, if username or password are missing
    if (!username || !name || !password) {
      res.status(400).json({
        msg: 'Parameters username, name and password are required'
      })
      return
    }
    
    User.findOne({ username }, (err, user) => {
        user.set({ username, name, password })
        user.save((err) => {
            if (err) {
              res.status(400).json({
                  msg: err.toString()
              })
              return
            }
            res.json({
              user_id: user._id
            })
        })
    })
})

users.delete('/:username', (req, res) => {
    const { username } = req.params

    User.findOne({ username }, (err, user) => {
        if (err) {
            res.status(400).json({
                msg: err.toString()
            })
            return
        }
        if (!user) {
            res.status(400).json({
                msg: "User not found."
            })
            return
        }
        User.deleteOne({ username }, (err) => {
            if (err) {
                res.status(400).json({
                    msg: err.toString()
                })
                return
            }
            res.json({
            })
        })
    })
})

export default users