// backend/controllers/userController.js

const User = require('../models/userModel');
const Role = require('../models/roleModel');
const Institution = require('../models/institutionModel');

/**
 * @desc    Get the profile of the currently logged-in user
 * @route   GET /api/users/me
 * @access  Private (All authenticated users)
 */
exports.getMe = async (req, res) => {
  // The 'auth' middleware already fetched the user, but we get the full profile here
  try {
    const user = await User.findById(req.user.id);
    if (!user) {
      return res.status(404).json({ message: 'User not found.' });
    }
    res.status(200).json(user);
  } catch (error) {
    res.status(500).json({ message: 'Server error fetching user profile.' });
  }
};


// =========================================================
// == For Institution Admins to Manage Their Staff        ==
// =========================================================

/**
 * @desc    Create a new staff user for the admin's institution
 * @route   POST /api/users
 * @access  Private (Admin)
 */
exports.createStaffUser = async (req, res) => {
  const { institution_id } = req.user;
  const { name, mobile, password } = req.body;

  if (!name || !mobile || !password) {
    return res.status(400).json({ message: 'Name, mobile, and password are required.' });
  }

  try {
    const staffRole = await Role.findByName('staff');
    if (!staffRole) {
      return res.status(500).json({ message: 'System error: Staff role not found.' });
    }

    const newUser = await User.create({
      institution_id,
      role_id: staffRole.id,
      name,
      mobile,
      password
    });

    res.status(201).json({ message: 'Staff user created successfully.', user: { id: newUser.id, mobile: newUser.mobile } });
  } catch (error) {
    if (error.code === 'ER_DUP_ENTRY') {
      return res.status(409).json({ message: 'A user with this mobile already exists.' });
    }
    res.status(500).json({ message: 'Error creating user.', error: error.message });
  }
};

/**
 * @desc    Get all users for the admin's institution
 * @route   GET /api/users
 * @access  Private (Admin)
 */
exports.getUsersByMyInstitution = async (req, res) => {
  try {
    const { institution_id } = req.user;
    const users = await User.findAllByInstitution(institution_id);
    res.status(200).json(users);
  } catch (error) {
    res.status(500).json({ message: 'Error fetching users for institution.', error: error.message });
  }
};

/**
 * @desc    Update a user's status (active/inactive) within an institution
 * @route   PATCH /api/users/:id/status
 * @access  Private (Admin)
 */
exports.updateUserStatus = async (req, res) => {
    const { institution_id } = req.user;
    const { id: targetUserId } = req.params;
    const { status } = req.body;

    if (!['active', 'inactive'].includes(status)) {
        return res.status(400).json({ message: 'Invalid status provided.' });
    }

    try {
        // Security check: ensure the user being modified belongs to the admin's institution
        const targetUser = await User.findById(targetUserId);
        if (!targetUser || targetUser.institution_id !== institution_id) {
            return res.status(404).json({ message: 'User not found in your institution.' });
        }
        // Prevent an admin from deactivating themselves
        if (targetUser.id === req.user.id) {
            return res.status(403).json({ message: "You cannot change your own status." });
        }

        await User.setStatus(targetUserId, status);
        res.status(200).json({ message: `User status successfully updated to ${status}.` });
    } catch(error) {
        res.status(500).json({ message: 'Error updating user status.', error: error.message });
    }
};