import secrets
from logging import getLogger

from fastapi import APIRouter

from apps.esia.sign import get_url
from clients import clients as c
from shared import exceptions as e
from shared.redis import client as cache

from . import schema as s

logger = getLogger(__name__)
router = APIRouter(
    prefix='/esia',
    tags=[
        'ESIA',
    ],
)


@router.get('/login', response_model=s.LoginURL)
async def login():
    url = get_url()
    return s.LoginURL(url=url)


@router.post('/callback')
async def callback(code: str):
    token = None
    for i in range(3):
        try:
            token = await c.esia_api.access_token(code)
            break
        except Exception:
            logger.warning(
                'Error occurred while accessing ESI API. Retrying...'
            )
            if i == 2:
                raise

    if token is None:
        raise e.BadRequestException

    await c.esia_api.get_user_info(token.access_token, token.id_token)

    access_token = secrets.token_urlsafe(32)
    cache.set(access_token, access_token)

    return s.Token(access_token=access_token)
