const router = require('express').Router();
const crypto = require('crypto');

const ERROR_MESSAGES = {
    invalid_credentials: 'Credenziali non valide',
    invalid_redirect: 'Redirect non autorizzato',
    csrf: 'Richiesta non valida, riprova'
};

router.get('/login', (req, res) => {
    const redirect = req.query.redirect || '';
    const errorKey = req.query.error;
    const error = ERROR_MESSAGES[errorKey] || null;

    const csrfToken = crypto.randomBytes(32).toString('hex');
    res.cookie('_csrf', csrfToken, {
        httpOnly: true,
        sameSite: 'strict',
        secure: process.env.NODE_ENV === 'production'
    });

    res.render('loginpage', { error, redirect, csrf_token: csrfToken });
});

module.exports = router;
