let express = require('express')
let router = express.Router()
const Errors = require('../lib/errors.js')
let {
    User, Ip, Ban
} = require('../models')
const cryptoRandomString = require("crypto-random-string")
const rateLimit = require("express-rate-limit");

const emailLimiter = rateLimit({
    windowMs: 60000,
    max: 1, // limit each IP to 100 requests per windowMs
    message: "{\"errors\":[{\"name\":\"rateLimit\",\"message\":\"You may only make 1 request to this endpoint per minute.\",\"status\":429}]}"
});

const registerLimit = rateLimit({
    windowMs: 60000 * 5, // 5 minutes
    max: 1, // limit each IP to 100 requests per windowMs
    message: "{\"errors\":[{\"name\":\"rateLimit\",\"message\":\"You may only make 1 request to this endpoint every 5 minutes.\",\"status\":429}]}"
});
function setUserSession(req, res, username, UserId, admin) {
    req.session.loggedIn = true
    req.session.username = username
    req.session.UserId = UserId
    res.cookie('username', username)
    //Not for security purposes, just so client side can determine
    //to show certain parts of ui or not (i.e. could trivially be spoofed
    //but the server would not accept any api requests)
    res.cookie('admin', !!admin)

    if(admin) { req.session.admin = true }
}
router.post('/oidfhuisadhi8243', emailLimiter, async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)

        let userParams = {
            username: req.body.username,
            email: req.body.email,
            hash: req.body.password,
            passkey: req.body.passkey,
            admin: false,
            bodyColor: '#ffffff',
            headColor: '#ffffff',
            leftLegColor: '#ffffff',
            rightLegColor: '#ffffff',
            leftArmColor: '#ffffff',
            rightArmColor: '#ffffff',
            koins: '250',
            currency2: '0',
            picture: 'default',
            developerMode: false,
            emailVerified: false,
            theme: 'light',
            emailToken: cryptoRandomString({length: 16})
        }
        let user = await User.create(userParams)
        await Ip.createIfNotExists(req.ip, user)

        setUserSession(req, res, user.username, user.id, userParams.admin)
        res.json(user.toJSON())
    } catch (e) { next(e) }
})
router.post('/null', async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)
        throw Errors.registrationsDisabled
    } catch (e) { next(e) }
})
router.post('/register', async (req, res, next) => {
    try {
        await Ban.isIpBanned(req.ip)
        throw Errors.registrationsDisabled
    } catch (e) { next(e) }
})

module.exports = router
