import passport from 'passport';
import { oneMonthInMs } from '../../shared/utils.js';
import { UserModel } from '../models/mongoose-models/UsersModel.js';
const cookieOptions = {
    path: '/',
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    maxAge: oneMonthInMs,
};
const authenticateAfter = (action, req, res) => {
    passport.authenticate('local')(req, res, () => {
        if (!req.session) {
            return res.status(500).json({ error: 'No session found' });
        }
        req.session.save(err => {
            if (err) {
                return res.status(500).json({ error: 'Error saving session' });
            }
            res.cookie('sessionID', req.sessionID, cookieOptions);
            return res
                .status(action === 'login' ? 200 : 201)
                .json({ success: `User ${action} successful` });
        });
    });
    return res;
};
export default (router) => {
    router.post('/api/register', async (req, res) => {
        const { email, password } = req.body;
        await UserModel.register({ email }, password);
        return authenticateAfter('register', req, res);
    });
    router.post('/api/login', async (req, res) => {
        const { email, password } = req.body;
        const authRes = await UserModel.authenticate()(email, password);
        if (authRes.error) {
            return res.status(401).json({ error: authRes.error });
        }
        return authenticateAfter('login', req, res);
    });
    router.get('/api/logout', (req, res) => {
        req.logout(err => {
            if (err)
                return err;
            res.json({ failed: 'User failed to logout' });
        });
        res.clearCookie('sessionID', cookieOptions).clearCookie('connect.sid', cookieOptions);
        res.status(200).json({ success: 'User logged out successfully' });
    });
    router.post('/api/update-password', async (req, res) => {
        const { email, oldPassword, newPassword } = req.body;
        const authRes = await UserModel.authenticate()(email, oldPassword);
        if (authRes.error) {
            return res.status(401).json({ error: authRes.error });
        }
        const user = await UserModel.findOne({ email });
        if (!user) {
            return res.status(404).json({ error: 'User not found' });
        }
        await user.changePassword(oldPassword, newPassword);
        await user.save();
        return res.status(200).json({ success: 'Password updated successfully' });
    });
};
