'use strict'

const jwt = require('jsonwebtoken')

const SUPER_SECRET = process.env.SUPER_ADMIN_JWT_SECRET || 'super-secret-change-in-production'

function signSuperToken(admin) {
  return jwt.sign(
    { id: admin.id, email: admin.email, name: admin.name, role: 'superadmin' },
    SUPER_SECRET,
    { expiresIn: '8h' }
  )
}

function verifySuperToken(req, res, next) {
  const token = req.cookies?.super_token || req.headers['x-super-token']
  if (!token) return res.status(401).json({ error: 'Não autenticado' })
  try {
    req.superAdmin = jwt.verify(token, SUPER_SECRET)
    next()
  } catch {
    res.status(401).json({ error: 'Token inválido ou expirado' })
  }
}

module.exports = { signSuperToken, verifySuperToken }
