const jwt = require('jsonwebtoken');
const { read } = require('../controllers/login');
require("dotenv").config();

const requireAuth = (req, res, next) => {
  const token = req.cookies.jwt;

  // Allow unauthenticated users to access the login and register pages
  if ((req.path === "/login" || req.path === "/register") && !token) {
    return next(); // If no token, allow access to login or register
  }

  if (token) {
    jwt.verify(token, process.env.JWT_SECRET, (error, decodedToken) => {
      if (error) {
        res.redirect("/login"); // Invalid token, redirect to login
      } else {
      // If user tries to access login or register and is already authenticated, redirect to dashboard
        if (req.path === "/login" || req.path === "/register") {
          res.redirect("/dashboard"); // Redirect logged-in user to dashboard
        } else {
          next(); // Allow access to other routes
        }
      }
    });
  } else {
    // Redirect unauthenticated users to login for all other routes
    res.redirect("/login");
  }
};

// Clear JWT token cookie by setting an expired cookie
const clearTokenCookie = (res) => {
  res.cookie('jwt', process.env.JWT_SECRET, { expires: new Date(0) });
};

const getCurrentUser = (req, res, next) => {
  const token = req.cookies.jwt;
  if (token) {
    jwt.verify(token, process.env.JWT_SECRET, async (error, decodedToken) => {
      if (error) {
        res.locals.user = null;
        next();
      } else {
        const user = await read(decodedToken.id);
        res.locals.user = user;
        next();
      }
    });
  } else {
    res.locals.user = null;
    next();
  }
};



module.exports = { requireAuth, clearTokenCookie, getCurrentUser};
