from dataclasses import asdict, dataclass
from urllib.parse import quote as urlquote
from urllib.parse import urlencode, urlparse

import requests
from aws_lambda_powertools.event_handler.exceptions import BadRequestError
from glom import glom

from config import KONVIVA_API_URL, KONVIVA_SECRET_KEY


class KonvivaError(BadRequestError):
    pass


@dataclass(frozen=True)
class KonvivaToken:
    login: str
    token: str
    nonce: str


def token(username: str) -> KonvivaToken:
    url = urlparse(KONVIVA_API_URL)._replace(
        path='/action/api/usuarios/token',
        query=f'login={urlquote(username)}',
    )

    headers = {
        'Authorization': f'KONVIVA {KONVIVA_SECRET_KEY}',
        'Content-Type': 'application/json',
    }

    r = requests.get(url.geturl(), headers=headers)
    r.raise_for_status()

    # Because Konviva does not return the proper HTTP status code
    if err := glom(r.json(), 'errors', default=None):
        raise KonvivaError(err)

    return KonvivaToken(**r.json())


def redirect_uri(token: KonvivaToken) -> str:
    url = urlparse(KONVIVA_API_URL)._replace(
        path='/action/acessoExterno',
        query=urlencode(asdict(token)),
    )

    return url.geturl()
