// backend/middleware/checkSubscription.js

const Subscription = require("../models/subscriptionModel");
const Institution = require("../models/institutionModel"); // You'll need your Institution model

/**
 * Middleware to check if the user's institution has an active subscription.
 * This should run AFTER the standard authentication middleware.
 */
const checkSubscription = async (req, res, next) => {
  try {
    // Super Admins or users not associated with an institution are allowed to pass.
    if (
      !req.user ||
      !req.user.institution_id ||
      req.user.role === "super_admin"
    ) {
      return next();
    }

    const { institution_id } = req.user;

    // 1. First, check if the institution itself is active
    const institution = await Institution.findById(institution_id);
    if (!institution || institution.status !== "active") {
      return res.status(403).json({
        message:
          "Your institution's account is inactive. Please contact support.",
      });
    }

    // 2. Then, check for a valid, active subscription
    const activeSubscription = await Subscription.findActiveByInstitutionId(
      institution_id
    );
    if (!activeSubscription) {
      return res.status(403).json({
        message:
          "Your institution does not have an active subscription. Please contact your administrator.",
      });
    }

    // If both checks pass, proceed to the requested route
    next();
  } catch (error) {
    console.error("Subscription Check Error:", error);
    res
      .status(500)
      .json({ message: "Server error during subscription validation." });
  }
};

module.exports = checkSubscription;
