const jwt    = require('jsonwebtoken');
const SECRET = process.env.JWT_SECRET || 'auxis_super_secret_key_2026';

function authMiddleware(req, res, next) {
  const header = req.headers['authorization'];
  if (!header) return res.status(401).json({ error: 'No token provided' });
  const token = header.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Malformed token' });
  try {
    req.user = jwt.verify(token, SECRET);
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid or expired token' });
  }
}

function adminOnly(req, res, next) {
  if (req.user?.role !== 'admin')
    return res.status(403).json({ error: 'Admin access only' });
  next();
}

function sign(payload) {
  return jwt.sign(payload, SECRET, { expiresIn: '30d' });
}

module.exports = { authMiddleware, adminOnly, sign };
