const passport = require("passport");
const model = require('../Model');  // Adjust path to your models
const { ExtractJwt } = require("passport-jwt");
const JwtStrategy = require('passport-jwt').Strategy;

require('dotenv').config();
// const secret = process.env.ACCESS_TOKEN;ACCESS_TOKEN

// Options for JWT extraction
const opts = {
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),  // Extract token from Authorization header
    secretOrKey: process.env.SECRET_KEY,  
};



// Defining Passport JWT strategy
passport.use(
    new JwtStrategy(opts, async function (jwt_payload, done) {
        try {
            // console.log("JWT Payload:", jwt_payload);

            // Find the user by ID from the JWT payload
            const user = await model.User.findById(jwt_payload.id);  // Assuming 'id' is part of the JWT payload
    
            if (user) {
                if(user.role=="superadmin"){
                    return done(null, user);
                }
                // console.log("token is ", user.number);
                // console.log("jwtpayload is ",jwt_payload.number);
              
                    // (user.number - jwt_payload.number < user.sessionAllowed
                
                // Directly compare the token stored in the database with the token in the payload
                if (user.number - jwt_payload.number < user.sessionAllowed) {  // Assuming jwt_payload contains a 'token' field
                    // console.log("all true");
                    
                    return done(null, user);  // User is authenticated, attach user to req.user
                } else {
                    // If tokens do not match, log the user out (token mismatch)
                    console.log("Token mismatch. Logging out.");
                    return done(null, false, { message: 'Session expired or logged in from another device.' });
                }
            } else {
                // Log if no user is found with the ID in the token
                // console.log("No user found with ID:", jwt_payload.id);
                return done(null, false, { message: 'User not found.' });
            }
        } catch (error) {
            console.error("Error during authentication:", error);
            return done(error, false);  // Error in authentication
        }
    })
);

module.exports = passport;
