import os
import urllib.parse
import jwt


from dotenv import load_dotenv
import aiohttp

def generate_google_oauth_redirect_uri(redirect_uri: str):
    # return redirect_uri
    load_dotenv(".env")
    query_params = {
        "redirect_uri": redirect_uri,
        "client_id": os.getenv("OAUTH_GOOGLE_CLIENT_ID"),
        "response_type": "code",
        "scope": " ".join([
            "openid",
            "profile",
            "email",
        ]),
        "access_type": "offline",
        # state: ...
    }

    query_string = urllib.parse.urlencode(query_params, quote_via=urllib.parse.quote)
    base_url = 'https://accounts.google.com/o/oauth2/v2/auth'
    return f"{base_url}?{query_string}"

async def get_customer_information_by_code(code: str, redirect_uri: str):
    google_token_url = "https://oauth2.googleapis.com/token"
    async with aiohttp.ClientSession() as session:
        async with session.post(
            url=google_token_url,
            data={
                "client_id": os.getenv("OAUTH_GOOGLE_CLIENT_ID"),
                "client_secret": os.getenv("OAUTH_GOOGLE_CLIENT_SECRET"),
                "grant_type" : "authorization_code",
                "redirect_uri": redirect_uri,
                "code": code,
            }
        ) as response:
            res = await response.json()
            if res.get('id_token'):
                data = jwt.decode(
                    res['id_token'],
                    algorithms=["RS256"],
                    options={"verify_signature": False},
                )

                return {
                    "data" : res,
                    "token_data" : data
                }
            else:
                return False