const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const db = require("../config/db"); // Assuming you have set up the database connection

const login = async (req, res) => {
  const { email_id, password } = req.body;

  try {
    const [results] = await db.query("SELECT * FROM users WHERE email = ?", [
      email_id,
    ]);

    if (results.length > 0) {
      const user = results[0];

      // Compare password using bcrypt (assuming passwords are hashed)
      const match = await bcrypt.compare(password, user.password);

      if (match) {
          
        // Generate an JWT access token (expires in 1 hour)
        const accessToken = jwt.sign(
          { user_id: user.id, email: user.email, role: user.role }, // Payload
          process.env.JWT_SECRET_KEY, // Secret key (store in an environment variable)
          { expiresIn: "24h" } // Token expiration (optional)
        );
        
        // // Generate a JWT token
        // const token = jwt.sign(
        //   { user_id: user.id, email: user.email, role: user.role }, // Payload
        //   process.env.JWT_SECRET, // Secret key (store in an environment variable)
        //   { expiresIn: '10h' } // Token expiration (optional)
        // );
        
        // Generate a refresh token (expires in 7 days)
        const refreshToken = jwt.sign(
          { user_id: user.id },
          process.env.JWT_REFRESH_SECRET_KEY,
          { expiresIn: "30d" }
        );
        
        // Store refresh token in the database (optional, for invalidation)
        await db.query("UPDATE users SET refresh_token = ? WHERE id = ?", [
          refreshToken,
          user.id,
        ]);

        res.json({
          message: "Login successful",
          accessToken: accessToken,
          refreshToken: refreshToken,
          user: {
            email: user.email,
            role: user.role,
            user_id: user.id,
          },
        });
      } else {
        res.status(401).json({ message: "Invalid credentials" });
      }
    } else {
      res.status(401).json({ message: "Invalid credentials" });
    }
  } catch (error) {
    res.status(500).json({ message: "An error occurred", error });
  }
};


// const login = async (req, res) => {
//   const { email_id, password } = req.body;

//   try {
//     const [results] = await db.query("SELECT * FROM users WHERE email = ?", [
//       email_id,
//     ]);

//     if (results.length > 0) {
//       const user = results[0];

//       // Compare password using bcrypt (assuming passwords are hashed)
//       const match = await bcrypt.compare(password, user.password);

//       if (match) {
//         // Generate Access Token (short-lived)
//         const accessToken = jwt.sign(
//           { user_id: user.id, email: user.email, role: user.role },
//           process.env.JWT_SECRET,
//           { expiresIn: "30m" } // Access token expires in 30 minutes
//         );

//         // Generate Refresh Token (long-lived)
//         const refreshToken = jwt.sign(
//           { user_id: user.id, email: user.email, role: user.role },
//           process.env.JWT_REFRESH_SECRET,
//           { expiresIn: "30d" } // Refresh token expires in 30 days
//         );

//         // Set the Refresh Token in httpOnly cookie
//         res.cookie("refreshToken", refreshToken, {
//           httpOnly: true,
//           secure: process.env.NODE_ENV === "production", // Use HTTPS in production
//           maxAge: 30 * 24 * 60 * 60 * 1000, // 7 days
//           sameSite: "Strict", // Prevents CSRF attacks
//         });

//         // Send Access Token in response (since it's short-lived, it doesn't need to be stored in a cookie)
//         res.json({
//           message: "Login successful",
//           user: {
//             email: user.email,
//             role: user.role,
//             user_id: user.id,
//           },
//           accessToken: accessToken, // Send access token as part of the response
//         });
//       } else {
//         res.status(401).json({ message: "Invalid credentials" });
//       }
//     } else {
//       res.status(401).json({ message: "Invalid credentials" });
//     }
//   } catch (error) {
//     res.status(500).json({ message: "An error occurred", error });
//   }
// };


const logout = (req, res) => {
  res.clearCookie("refreshToken", {
    httpOnly: true,
    secure: process.env.NODE_ENV === "production",
    sameSite: "Strict",
  });
  res.json({ message: "Logged out successfully" });
};


const refreshAccessToken = async (req, res) => {
  const { refreshToken } = req.body;

  if (!refreshToken) {
    return res.status(403).json({ message: "Refresh token is required" });
  }

  try {
    // Verify the refresh token
    const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET_KEY);

    // // Optionally check if the refresh token is stored in the database
    // const [user] = await db.query("SELECT * FROM users WHERE id = ?", [
    //   decoded.user_id,
    // ]);
    // if (!user || user.refresh_token != refreshToken) {
    //   return res.status(403).json({ message: "Invalid refresh token", user_id:decoded.user_id  });
    // }

    // Generate a new access token
    const accessToken = jwt.sign(
      { user_id: decoded.user_id, email: decoded.email, role: decoded.role },
      process.env.JWT_SECRET_KEY,
      { expiresIn: "24h" }
    );

    res.json({ accessToken: accessToken });
  } catch (error) {
    res.status(403).json({ message: "Invalid or expired refresh token" });
  }
};

// const refreshToken = async (req, res) => {
//   const refreshToken = req.cookies.refreshToken;

//   if (!refreshToken) {
//     return res.status(401).json({ message: "No refresh token provided" });
//   }

//   try {
//     // Verify the refresh token
//     const decoded = jwt.verify(refreshToken, process.env.JWT_REFRESH_SECRET);

//     // Generate a new access token using the decoded data from the refresh token
//     const accessToken = jwt.sign(
//       { user_id: decoded.user_id, email: decoded.email, role: decoded.role },
//       process.env.JWT_SECRET,
//       { expiresIn: "30m" } // New access token with short expiration
//     );

//     res.json({ accessToken });
//   } catch (error) {
//     res.status(403).json({ message: "Invalid refresh token" });
//   }
// };




module.exports = { login, logout, refreshAccessToken };
