"""
Authentication Middleware
API key authentication for protected endpoints
"""

from functools import wraps
from flask import request, g, current_app
from app.utils.api_response_mixin import ApiResponseMixin
from app.utils.helpers import get_logger


class AuthMiddleware(ApiResponseMixin):
    """Middleware for API key authentication"""

    def __init__(self):
        self.logger = get_logger("auth_middleware")

    def authenticate_api_key(self):
        """
        Authenticate request using API key from header

        Returns:
            True if authenticated, False otherwise
        """
        api_key = request.headers.get('X-API-Key') or request.headers.get('Authorization')
        self.logger.debug(f"Headers: %s", request.headers)
        self.logger.debug(f"Extracted API key: {api_key}")

        if not api_key:
            return False

        # Remove 'Bearer ' prefix if present
        if api_key.startswith('Bearer '):
            api_key = api_key[7:]

        # Get valid API keys from config
        valid_keys = current_app.config.get('API_KEYS', [])
        self.logger.debug(f"Valid API keys: {valid_keys}")

        if api_key in valid_keys:
            g.api_key = api_key
            return True

        return False

    def require_api_key(self, f):
        """
        Decorator to require API key authentication for a route

        Usage:
            @app.route('/protected')
            @auth_middleware.require_api_key
            def protected_route():
                return 'This is protected'
        """
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not self.authenticate_api_key():
                self.logger.warning(f"Unauthorized API access attempt to {request.path}")
                return self.unauthorized({
                    "message": "Valid API key required",
                    "error": "Missing or invalid X-API-Key header"
                })

            return f(*args, **kwargs)

        return decorated_function


# Global auth middleware instance
auth_middleware = AuthMiddleware()