// middleware/auth.js

const jwt = require("jsonwebtoken");
const pool = require("../config/db"); // Your database connection pool

const auth = async (req, res, next) => {
  let token;

  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      // 1. Get token from header
      token = req.headers.authorization.split(" ")[1];

      // 2. Verify token
      const decoded = jwt.verify(token, process.env.JWT_SECRET);

      // 3. Get user from the DB and attach to request object
      // This ensures the user still exists and is active.
      const [userRows] = await pool.query(
        `SELECT u.id, u.institution_id, r.name as role 
         FROM users u 
         JOIN roles r ON u.role_id = r.id 
         WHERE u.id = ? AND u.status = 'active'`,
        [decoded.id]
      );
      
      if (userRows.length === 0) {
        return res.status(401).json({ message: "User not found or inactive." });
      }

      const user = userRows[0];
      req.user = user; // { id: 1, institution_id: 101, role: 'admin' }

      // 4. (CRITICAL) Check for active subscription for non-super_admin users
      if (user.role !== 'super_admin' && user.institution_id) {
        const [subRows] = await pool.query(
          `SELECT status FROM subscriptions WHERE institution_id = ? AND status = 'active' AND end_date >= CURDATE()`,
          [user.institution_id]
        );
        
        if (subRows.length === 0) {
          return res.status(403).json({ message: "Subscription is inactive or expired. Please contact support." });
        }
      }

      next();
    } catch (error) {
      console.error(error);
      return res.status(401).json({ message: "Not authorized, token failed." });
    }
  }

  if (!token) {
    return res.status(401).json({ message: "Not authorized, no token." });
  }
};

// Optional but recommended: Role-based authorization middleware
const authorize = (...roles) => {
  return (req, res, next) => {
    if (!req.user || !roles.includes(req.user.role)) {
      return res.status(403).json({ message: "User role not authorized for this action." });
    }
    next();
  };
};


module.exports = { auth, authorize };