/**
 * superAdminAuth.js
 * Independent SuperAdmin Master Authentication Middleware.
 * Enforces master secret keys and tokens isolated from tenant user accounts.
 */

const jwt = require('jsonwebtoken');

const SUPERADMIN_JWT_SECRET = process.env.SUPERADMIN_JWT_SECRET || 'superadmin-master-auth-secret-key-2026';
const SUPERADMIN_MASTER_KEY = process.env.SUPERADMIN_MASTER_KEY || 'SA-MASTER-KEY-2026-X99';

function superAdminAuth(req, res, next) {
  // Allow health check endpoint
  if (req.path === '/api/health' || req.path === '/api/auth/login') {
    return next();
  }

  const masterHeader = req.headers['x-superadmin-key'];
  if (masterHeader && masterHeader === SUPERADMIN_MASTER_KEY) {
    req.isSuperAdmin = true;
    return next();
  }

  const authHeader = req.headers.authorization;
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'SuperAdmin master token or X-SuperAdmin-Key header required' });
  }

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, SUPERADMIN_JWT_SECRET);
    if (decoded.role !== 'super_admin_master') {
      return res.status(403).json({ error: 'Access denied. SuperAdmin master role required.' });
    }
    req.superAdmin = decoded;
    req.isSuperAdmin = true;
    next();
  } catch (err) {
    return res.status(401).json({ error: 'Invalid or expired SuperAdmin master token', details: err.message });
  }
}

module.exports = { superAdminAuth, SUPERADMIN_JWT_SECRET, SUPERADMIN_MASTER_KEY };
