from collections import defaultdict
from urllib.parse import parse_qs

import authlib.oauth2.rfc6749.requests as requests
from aws_lambda_powertools.utilities.data_classes.api_gateway_proxy_event import (
    APIGatewayProxyEventV2,
)


class APIGatewayOAuth2Payload(requests.OAuth2Payload):
    def __init__(self, request: APIGatewayProxyEventV2):
        self._request = request

    @property
    def decoded_body(self):
        # TODO
        body = parse_qs(self._request.decoded_body, keep_blank_values=True)
        return {k: v[0] if len(v) == 1 else v for k, v in body.items()}

    @property
    def data(self):
        """Combines query string parameters and the request body"""
        return self._request.query_string_parameters | self.decoded_body

    @property
    def datalist(self) -> dict[str, list]:
        values = defaultdict(list)

        for k, v in self.data.items():
            values[k].extend([v])
        return values


class APIGatewayJsonRequest(requests.JsonRequest):
    def __init__(self, request: APIGatewayProxyEventV2):
        uri = f'https://{request.request_context.domain_name}'

        super().__init__(
            request.request_context.http.method,
            uri,
            request.headers,
        )


class APIGatewayOAuth2Request(requests.OAuth2Request):
    def __init__(self, request: APIGatewayProxyEventV2):
        uri = f'https://{request.request_context.domain_name}'

        super().__init__(
            request.request_context.http.method,
            uri,
            headers=request.headers,
        )
        self._request = request
        self.payload = APIGatewayOAuth2Payload(request)

    @property
    def args(self):
        # @TODO
        return self._request.query_string_parameters

    @property
    def form(self) -> dict[str, str]:
        # @TODO
        return self.payload.decoded_body
