'use strict';

const jwt = require('jsonwebtoken');

const JWT_SECRET = process.env.JWT_SECRET || 'deploypro-jwt-secret-change-in-production!';
const JWT_EXPIRY = '12h';

function requireAuth(req, res, next) {
  const auth  = req.headers['authorization'];
  const token = auth && auth.startsWith('Bearer ') ? auth.slice(7) : null;
  if (!token) return res.status(401).json({ error: 'Authentication required' });
  try {
    req.user = jwt.verify(token, JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

function requireSuperAdmin(req, res, next) {
  if (req.user && req.user.role === 'superadmin') return next();
  res.status(403).json({ error: 'Superadmin access required' });
}

module.exports = { requireAuth, requireSuperAdmin, JWT_SECRET, JWT_EXPIRY };
