const router = require(`express`).Router()

const usersModel = require(`../models/users`)


// IMPORTANT
// Obviously, in a production release, you should never have the code below, as it allows a user to delete a database collection
// The code below is for development testing purposes only 
router.post(`/users/reset_user_collection`, (req,res,next) => 
{
    // delete all users from collection
    usersModel.get().then(documents => 
    {
        documents.forEach(document =>
        { 
            usersModel.doc(document.id).delete() 
        })

        // add administrator user
        const adminPassword = `123-qwe_QWE`

        usersModel.add({name:"Administrator",email:"admin@admin.com",password:adminPassword})
        .then(() => 
        {
            res.json(req.body)
        })
        .catch(err => next(err))
    })
})
           

router.post(`/users/register/:name/:email/:password`, (req, res,next) =>
{
    // If a user with this email does not already exist, then create new user    
    usersModel.where('email', '==', req.params.email).get()
    .then(documents =>
    {
        let numberOfRecordsRead = 0
        documents.forEach(document =>
        { 
            numberOfRecordsRead++
        })
                  
        if (numberOfRecordsRead !== 0)
        {
            res.json({errorMessage: `User already exists`})
        } 
        else
        {            
            usersModel.add({name: req.params.name, email: req.params.email, password: req.params.password})
            .then(() => 
            {
                res.json(req.body)
            })            
        }
    })
    .catch(err => next(err))
})


module.exports = router