var express = require('express');
var router = express.Router();
const passport = require('../passport-config');
const models = require("../schemas/models");

const User = models.User;

/* GET home page. */
router.get('/', function(req, res, next) {
    // res.render('login',{ user : req.user });
    console.log('heeeeeeeeeeee');
    res.redirect('/announcements');
});


router.get('/login', function(req, res, next) {
    res.render('login', { user: req.user, messages: req.flash('error') });
});


router.post('/login', function(req, res, next) {
    passport.authenticate('local', function(err, user, info) {
        if (err) { // Handle unexpected errors
            return next(err);
        }
        if (!user) {
            console.log('invalid username or password');
            res.status(400).render('login', { error: 'Invalid username or password' });
            return;
        }
        req.logIn(user, function(err) {
            if (err) {
                return next(err);
            }
            return res.redirect('/announcements');
        });
    })(req, res, next);
});



router.get('/dashboard', isAuthenticated, function(req, res, next) {
    res.render('dashboard', { user: req.user });
});


router.get('/register', function(req, res) {
    res.render('register', { user : req.user });
});


router.post('/register', async function(req, res) {
    try {
        const { username, password, role } = req.body;
        const existingUser = await User.findOne({ username });

        if (existingUser) {
            return res.render('register', { error: ' This user already exists.' });
        }

        const newUser = new User({
            username: username,
            password: password,
            isAgent: role === 'agent'
        });

        await newUser.save();

        //passport.authenticate('local')(req, res, function () {
        res.redirect('/login');
        //});
    } catch (error) {
        res.render('register', { error: error.message });
    }
});



router.get('/logout', isAuthenticated, function(req, res, next) {
    req.logout(function(err) {
        if (err) {
            return next(err);
        }
        res.redirect('/');
    });
});

function isAuthenticated(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    }
    res.redirect('/login');
}
const setUserIfAuthenticated = (req, res, next) => {
    if (req.isAuthenticated()) {
        req.user = req.user;
    }
    next();
};

module.exports = {
    router: router,
    isAuthenticated: isAuthenticated,
    setUserIfAuthenticated:  setUserIfAuthenticated,
};