import type { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { env } from '../../config/env'

interface JwtPayload {
  sub: string   // userId (tenantId)
  role: string
}

export function authMiddleware(req: Request, res: Response, next: NextFunction): void {
  const header = req.headers.authorization
  // Aceita token via query string para uso em <img src="...?token=...">
  const queryToken = typeof req.query['token'] === 'string' ? req.query['token'] : null

  if (!header?.startsWith('Bearer ') && !queryToken) {
    res.status(401).json({ error: 'Token não fornecido' })
    return
  }

  const token = header?.startsWith('Bearer ') ? header.slice(7) : queryToken!
  try {
    const payload = jwt.verify(token, env.JWT_SECRET) as JwtPayload
    req.tenantId = payload.sub
    req.userRole = payload.role
    next()
  } catch {
    res.status(401).json({ error: 'Token inválido ou expirado' })
  }
}
