"""Shared dependencies for v1 routes.

``check_ip_whitelist`` is always present; ``get_current_user`` is wired
only when ``use_auth == "yes``.
"""

from __future__ import annotations

from fastapi import Depends, HTTPException, Request, status

from {{ cookiecutter.project_name }}.config.settings import settings

DEFAULT_WHITELIST = ["127.0.0.1", "::1"]


async def check_ip_whitelist(request: Request) -> None:
    """Reject requests from non-whitelisted IPs.

    Defaults to ``["127.0.0.1", "::1"]`` (no hardcoded production IPs);
    override via ``IP_WHITELIST`` in env.
    """
    client = request.client.host if request.client else None
    whitelist = settings.ip_whitelist or DEFAULT_WHITELIST
    if client and client not in whitelist:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail=f"IP {client} not allowed",
        )


{% if cookiecutter.use_auth == "yes" and cookiecutter.use_db == "yes" %}
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer

from {{ cookiecutter.project_name }}.services.auth_service import AuthService

_bearer = HTTPBearer()


async def get_current_user(
    credentials: HTTPAuthorizationCredentials = Depends(_bearer),
    auth: AuthService = Depends(AuthService),
) -> str:
    """Resolve the current user from the bearer token (JWT).

    Returns the username/subject of the token. Only present when
    ``use_auth == "yes"``.
    """
    return await auth.decode_access_token(credentials.credentials)
{% endif %}