// controllers/authController.js
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const User = require("../models/userModel");
const Subscription = require("../models/subscriptionModel");
const Institution = require("../models/institutionModel");

exports.login = async (req, res) => {
  const { mobile, password } = req.body;
  if (!mobile || !password) {
    return res
      .status(400)
      .json({ message: "Please provide mobile and password." });
  }

  try {
    const user = await User.findByMobile(mobile);
    if (!user || user.status === "inactive") {
      return res
        .status(401)
        .json({ message: "Invalid credentials or user inactive." });
    }

    const isMatch = await bcrypt.compare(password, user.password_hash.trim());
    if (!isMatch) {
      return res.status(401).json({ message: "Invalid credentials." });
    }

    // --- CRITICAL CHECK BLOCK (UPDATED) ---
    if (user.role !== "super_admin" && user.institution_id) {
      // ADDED: Step 1 - Check if the institution itself is active
      const institution = await Institution.findById(user.institution_id);
      if (!institution || institution.status !== "active") {
        return res.status(403).json({
          message:
            "Your institution's account is inactive. Please contact support.",
        });
      }

      // Step 2 - Check for an active subscription (your existing code, which is correct)
      const activeSub = await Subscription.findActiveByInstitutionId(
        user.institution_id
      );
      if (!activeSub) {
        return res.status(403).json({
          message:
            "Your institution does not have an active subscription. Please contact support.",
        });
      }
    }
    // --- END OF CRITICAL CHECK BLOCK ---

    const payload = {
      id: user.id,
      institution_id: user.institution_id,
      role: user.role,
      name: user.name,
      mobile: user.mobile,
    };
    const token = jwt.sign(payload, process.env.JWT_SECRET, {
      expiresIn: "1d",
    });

    res.json({ token, user: { name: user.name, role: user.role } });
  } catch (error) {
    console.error("Login Error:", error); // Good for debugging
    res.status(500).json({ message: "Server error during login." });
  }
};

exports.loginAs = async (req, res) => {
  const { targetUserId } = req.body;
  const impersonator = req.user; // The logged-in super_admin from the 'auth' middleware

  if (!targetUserId) {
    return res.status(400).json({ message: "Target User ID is required." });
  }

  try {
    // 1. Find the user to be impersonated
    const targetUser = await User.findById(targetUserId);

    // 2. Perform security validations
    if (!targetUser) {
      return res.status(404).json({ message: "Target user not found." });
    }
    if (targetUser.id === impersonator.id) {
      return res.status(400).json({ message: "Cannot impersonate yourself." });
    }
    if (targetUser.role === "super_admin") {
      return res
        .status(403)
        .json({ message: "Cannot impersonate another Super Admin." });
    }
    if (targetUser.status === "inactive") {
      return res
        .status(403)
        .json({ message: "Cannot log in as an inactive user." });
    }

    // 3. Create the impersonation JWT payload
    const payload = {
      id: targetUser.id,
      institution_id: targetUser.institution_id,
      role: targetUser.role,
      name: targetUser.name,
      mobile: targetUser.mobile,
      impersonator_id: impersonator.id,
      impersonator_role: impersonator.role,
    };

    // 4. Sign the new token with a shorter expiry for added security
    const impersonationToken = jwt.sign(payload, process.env.JWT_SECRET, {
      expiresIn: "2h", // A 2-hour session should be enough for debugging
    });

    // 5. [Recommended] Log this sensitive action for auditing
    console.log(
      `AUDIT: Super Admin '${impersonator.id}' is impersonating User '${targetUser.id}' (${targetUser.mobile}).`
    );
    // In a real system, you would write this to an audit_logs table in the database.

    // 6. Send the new token and target user info to the frontend
    res.json({
      message: `Successfully initiated impersonation session as ${targetUser.name}.`,
      token: impersonationToken,
      user: {
        // Send the target user's info for immediate UI update
        name: targetUser.name,
        role: targetUser.role,
      },
    });
  } catch (error) {
    console.error("Error during impersonation login:", error);
    res.status(500).json({ message: "Server error during login-as process." });
  }
};
