const express = require("express");
const router = express.Router();
const path = require("path");
const fs = require("fs");
const bcrypt = require('bcrypt');


router.get("/session", (req, res) => {
	if (req.session && req.session.authenticated) {
		res.status(200).json({ authenticated: true, user: req.session.user, sessionID: req.sessionID });
	} else {
		res.status(401).json({ authenticated: false });
	}
});

router.post("/login", (req, res) => {
	const { username, password } = req.body;
	// Locate user in global.authUsers [{username, password}]. password is bcrypted.
	const user = global.authUsers.find(u => u.username === username);
	if (user) {
		// Compare password
		bcrypt.compare(password, user.passwordHash, (err, result) => {
			if (result) {
				// Passwords match
				req.session.authenticated = true;
				req.session.user = { username: user.username, fullname: user.fullname, remember: req.body.remember || false };
				res.status(200).json({ success: true, message: 'Login successful' });
			} else {
				// Passwords don't match
				res.status(401).json({ success: false, message: 'Invalid credentials' });
			}
		});
	} else {
		// User not found
		res.status(401).json({ success: false, message: 'Invalid credentials' });
	}
});

router.post("/logout", (req, res) => {
	req.session.destroy(err => {
		if (err) {
			return res.status(500).json({ success: false, message: 'Logout failed' });
		}
		res.status(200).json({ success: true, message: 'Logged out successfully' });
	});
});

module.exports = router;