const express = require('express');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const app = express();
dotenv.config();

// Middleware to verify token
exports.verifyToken = (req, res, next) => {
  const token = req.headers['authorization']?.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    res.status(401).json({ message: 'Invalid token' });
  }
};


// const session = require('express-session');

// // Use the session middleware
// app.use(session({
//   secret: process.env.SESSION_SECRET || 'your-secret-key', // You should set this secret in your .env file
//   resave: false, // Don't save session if unmodified
//   saveUninitialized: true, // Save uninitialized sessions
//   cookie: { 
//     maxAge: 1000 * 60 * 60, // 1 hour session expiry (customize as needed)
//   //  secure: process.env.NODE_ENV === 'production' // Ensure cookies are sent over HTTPS in production
//   }
// }));



function ensureAuthenticated(req, res, next) {

  if (req.isAuthenticated || req.session.user || req.headers.authorization) {
    return next();
  }
 
  res.redirect('/login');
}


module.exports = ensureAuthenticated;
