/**
 * Authentication Middleware
 * Verifies JWT tokens and protects routes
 */

import { Request, Response, NextFunction } from 'express';
import { AuthService } from '../services/auth.service';

/**
 * Extend Express Request to include user property
 */
declare global {
  namespace Express {
    interface Request {
      user?: {
        user_id: string;
      };
    }
  }
}

/**
 * Authentication middleware
 * Protects routes by verifying JWT tokens
 */
export const authenticate = (req: Request, res: Response, next: NextFunction): void => {
  try {
    // Extract token from Authorization header
    const authHeader = req.headers.authorization;
    const token = AuthService.extractTokenFromHeader(authHeader);

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

    // Verify token
    const payload = AuthService.verifyToken(token);

    // Attach user info to request
    req.user = {
      user_id: payload.user_id,
    };

    next();
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Authentication failed';
    res.status(401).json({
      success: false,
      error: message,
    });
  }
};

/**
 * Optional authentication middleware
 * Attaches user info if token is present, but doesn't block if missing
 */
export const optionalAuthenticate = (req: Request, _res: Response, next: NextFunction): void => {
  try {
    const authHeader = req.headers.authorization;
    const token = AuthService.extractTokenFromHeader(authHeader);

    if (token) {
      const payload = AuthService.verifyToken(token);
      req.user = {
        user_id: payload.user_id,
      };
    }
  } catch {
    // Ignore errors, continue without user
  }

  next();
};
