// @WHO:   vps-deploy/api/kds/src/middleware/auth.ts
// @WHAT:  JWT authentication middleware for protected routes
// @PART:  auth
// @ENTRY: authMiddleware

import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret';

// @FLOW:     AUTH_VERIFY
// @CALLS:    jwt.verify
// @MUTATES:  req.user (attach decoded payload)
export function authMiddleware(req: Request, res: Response, next: NextFunction) {
  const authHeader = req.headers.authorization;
  if (!authHeader?.startsWith('Bearer ')) {
    return res.status(401).json({ error: 'Missing authorization header' });
  }

  try {
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, JWT_SECRET);
    (req as any).user = decoded;
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }
}
