import logging
from fastapi.responses import JSONResponse

from intranet.trip.ext_api.src.config import settings
from intranet.trip.ext_api.src.api.auth import get_user_by_request

logger = logging.getLogger(__name__)


async def authentication(request, call_next):
    blackbox_user = await get_user_by_request(request)
    response = None

    if blackbox_user.get('status', {}).get('value') != 'VALID':
        logger.warning('User auth: FAILED to %s', request.url)
        return JSONResponse(
            status_code=401,
            content={'detail': 'Unauthorized'},
        )

    uid = blackbox_user['uid']['value']
    if uid not in settings.UID_PROVIDERS.values():
        logger.warning('User auth: unknown uid %s', uid)
        return JSONResponse(
            status_code=401,
            content={'detail': 'Unauthorized'},
        )

    request.state.user_uid = uid

    if not response:
        response = await call_next(request)

    logger.info(
        '%s>%s: %s',
        request.method,
        response.status_code,
        request.url,
    )
    return response
