"""API dependencies, e.g., for authentication and validation."""

import logging

from fastapi import HTTPException, Request
from fastapi.security import APIKeyHeader
from starlette.status import HTTP_403_FORBIDDEN

from src.config import settings

# Define API key header
API_KEY_NAME = "X-API-Key"
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
logger = logging.getLogger(__name__)


async def verify_api_key(request: Request) -> None:
    """Verify API key from request headers."""
    if not settings.API_KEY:
        return

    api_key = request.headers.get(API_KEY_NAME, "").strip()
    is_valid_key = api_key == settings.API_KEY

    # Log the request
    logger.info(
        f"Request: {request.method} {request.url.path} | "
        f"IP: {request.client.host if request.client else 'Unknown'} | "
        f"Valid API Key: {is_valid_key}",
    )

    if not is_valid_key:
        raise HTTPException(
            status_code=HTTP_403_FORBIDDEN,
            detail="Invalid API Key",
        )
