/**
 * Authentication Middleware
 * Mecánicas Diesel - ERP Suite
 */

import { Response, NextFunction } from 'express';
import { AuthRequest } from '../types';
import { verifyToken } from '../utils/jwt.utils';

/**
 * Authentication middleware - verifies JWT token
 */
export function authMiddleware(
  req: AuthRequest,
  res: Response,
  next: NextFunction
): void {
  try {
    const authHeader = req.headers.authorization;

    if (!authHeader) {
      res.status(401).json({
        success: false,
        error: { message: 'No authorization token provided', code: 'NO_TOKEN' },
      });
      return;
    }

    const parts = authHeader.split(' ');
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      res.status(401).json({
        success: false,
        error: { message: 'Invalid authorization format', code: 'INVALID_TOKEN_FORMAT' },
      });
      return;
    }

    const payload = verifyToken(parts[1]);

    if (!payload) {
      res.status(401).json({
        success: false,
        error: { message: 'Invalid or expired token', code: 'INVALID_TOKEN' },
      });
      return;
    }

    req.user = payload;
    req.tenantId = payload.tenantId;
    next();
  } catch (error) {
    res.status(401).json({
      success: false,
      error: { message: 'Authentication failed', code: 'AUTH_ERROR' },
    });
  }
}
