/**
 * Allows only Admin. Use for create/update/delete users and other admin-only actions.
 * Accepts role names (roles) or role IDs (roleIds) from JWT; if missing, fetches roles from DB.
 * Role name check is case-insensitive ('Admin', 'admin', 'ADMIN' all work).
 */
const { ROLE_IDS } = require('../constants/hseRoles');

const ADMIN_ROLE_ID = ROLE_IDS.ADMIN;

const normalizeRoleNames = (roles) => {
  if (Array.isArray(roles)) return roles.map((r) => String(r || '').toLowerCase());
  if (typeof roles === 'string') return roles.split(',').map((s) => s.trim().toLowerCase());
  return [];
};

const checkAdminFromToken = (req) => {
  const userRoles = normalizeRoleNames(req.user.roles || []);
  const roleIds = (req.user.roleIds || []).map((id) => Number(id)).filter((n) => !Number.isNaN(n));
  return userRoles.includes('admin') || roleIds.includes(ADMIN_ROLE_ID);
};

const verifyAdmin = async (req, res, next) => {
  const send403 = () =>
    res.status(403).json({
      success: false,
      message: 'Access denied. Admin privileges required.'
    });

  try {
    if (!req.user) {
      return res.status(401).json({
        success: false,
        message: 'Access denied. User not authenticated.'
      });
    }

    if (checkAdminFromToken(req)) return next();

    // Token missing or invalid role info – resolve from DB
    try {
      const { getUserById } = require('../repositories/userRepository');
      const userId = req.user.userId || req.user.user_id;
      if (!userId) return send403();

      const user = await getUserById(userId);
      if (!user || !(user.roles && user.roles.length)) return send403();

      const roleIds = (user.roles || []).map((r) => Number(r.role_id)).filter((n) => !Number.isNaN(n));
      const roleNames = normalizeRoleNames((user.roles || []).map((r) => (r && (r.role_name ?? r.roleName)) || ''));

      if (roleIds.includes(ADMIN_ROLE_ID) || roleNames.includes('admin')) return next();
      return send403();
    } catch (err) {
      console.error('Admin verification DB fallback error:', err);
      return send403();
    }
  } catch (error) {
    console.error('Admin verification error:', error);
    return res.status(500).json({
      success: false,
      message: 'Admin verification failed',
      error: error.message
    });
  }
};

module.exports = verifyAdmin;

