let bcrypt = require('bcryptjs')
let multer = require('multer')
let express = require('express')
let router = express.Router()
const auth = require('../lib/auth')
var Recaptcha = require('express-recaptcha').RecaptchaV3;
var recaptcha = new Recaptcha('6LdlbrwZAAAAAKvtcVQhVl_QaNOqmQ4PgyW3SKHy', '6LdlbrwZAAAAAMAWPVDrL8eNPxrws6AMDtLf1bgd');
var reCAPTCHASecret = "6LdlbrwZAAAAAKvtcVQhVl_QaNOqmQ4PgyW3SKHy";
const Errors = require('../lib/errors.js')
let {
    User, Post, ProfilePicture, AdminToken, Thread, Category, Sequelize, Ip, Ban, sequelize
} = require('../models')
let pagination = require('../lib/pagination.js')

function setUserSession(req, res, username, UserId, admin) {
    req.userData.loggedIn = true
    req.userData.username = username
    req.userData.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.userData.admin = true }
}
router.get('/', async function(req, res) {
    if(req.userData.admin) {
        try {
            let sortFields = {
                createdAt: 'X.id',
                username: 'X.username',
                threadCount: 'threadCount',
                postCount: 'postCount',
                email: 'X.email',
                bot: 'X.bot'
            };
            let offset = Number.isInteger(+req.query.offset) ? +req.query.offset : 0;
            let havingClause = '';

            if (req.query.role === 'admin') {
                havingClause = 'HAVING Users.admin = true';
            } else if (req.query.role === 'user') {
                havingClause = 'HAVING Users.admin = false';
            } else {
                havingClause = '';
            }


            if (req.query.search) {
                //I.e. if there is not already a HAVING clause
                if (!havingClause.length) {
                    havingClause = 'HAVING ';
                } else {
                    havingClause += ' AND ';
                }

                havingClause += 'Users.username LIKE $search';
            }

            let sql = `
			SELECT X.username, X.admin, X.bot, X.email, X.createdAt, X.postCount, COUNT(Threads.id) as threadCount
			FROM (
				SELECT Users.*, COUNT(Posts.id) as postCount
				FROM Users
				LEFT OUTER JOIN Posts
				ON Users.id = Posts.UserId
				GROUP BY Users.id
				${havingClause}
			) as X
			LEFT OUTER JOIN Threads
			ON X.id = Threads.UserId
			GROUP BY X.id
			ORDER BY ${sortFields[req.query.sort] || 'X.id'} ${req.query.order === 'asc' ? 'ASC' : 'DESC'}
			LIMIT 15
			OFFSET ${offset}
		`;

            let users = await sequelize.query(sql, {
                model: User,
                bind: {search: req.query.search + '%'}
            });

            res.json(users)
            res.json(users)
        } catch (e) { next(e) }
    } else {
        res.status(401)
        res.json({
            errors: [Errors.requestNotAuthorized]
        })
    }
})

module.exports = router;
