const authRouter = require('express').Router()
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const { JWT_TOKEN, SALT } = require('./key')
const { getResponse } = require('../utils/common')
const { getUsers, addUser, getUserByEmail } = require('../controller')
const checkRequiredMidleware = require('../midlewares/checkRequired.midleware')

authRouter.get('/users', async (req, res) => {
    let error = null
    const dishData = await getUsers().catch((e) => error = e.message)
    res.send(getResponse(error, dishData))
})

authRouter.post(
    '/register',
    checkRequiredMidleware(['email', 'password']),
    async (req, res) => {
        const { email, password } = req.body
        const hash = await bcrypt.hash(password, SALT)
        let error = null
        const user = await addUser({ email, hash }).catch((e) => error = e.message)
        res.send(getResponse(error, user))
    },
)

authRouter.post(
    '/login',
    checkRequiredMidleware(['email', 'password']),
    async (req, res) => {
        const { email, password } = req.body;
        let error = null
        const user = await getUserByEmail({ email }).catch((e) => error = e.message)
        if (user) {
            const passwordCorrect = await bcrypt.compare(password, user.hash)
            if (passwordCorrect) {
                // eslint-disable-next-line no-undef
                const token = jwt.sign({ email }, JWT_TOKEN)
                res.send({ email, token })
                return
            }
        }
        res.status(400).send('Incorrect email or password')
    },
)

module.exports = authRouter
