from google.oauth2 import id_token
from google.auth.transport import requests
import os
from dotenv import load_dotenv
import logging
from cryptography.fernet import Fernet

load_dotenv()

GOOGLE_CLIENT_ID = os.getenv('GOOGLE_CLIENT_ID')

# Generate a key for encryption and decryption
# You must keep this key secure! If you lose it you will not be able to decrypt your data.
# Store this key in a configuration file or environment variable.
fernet_key = Fernet.generate_key()
cipher_suite = Fernet(fernet_key)

# Function to encrypt the refresh token
def encrypt_refresh_token(refresh_token: str) -> str:
    return cipher_suite.encrypt(refresh_token.encode()).decode()

# Function to decrypt the refresh token
def decrypt_refresh_token(encrypted_refresh_token: str) -> str:
    return cipher_suite.decrypt(encrypted_refresh_token.encode()).decode()

# This is the verify_google_token function
def verify_google_token(token: str):
    try:
        # Specify the CLIENT_ID of the app that accesses the backend
        idinfo = id_token.verify_oauth2_token(token, requests.Request(), GOOGLE_CLIENT_ID)

        if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
            raise ValueError('Wrong issuer.')

        # Here, we would have some logic to obtain the refresh token through your OAuth flow
        # For the sake of this example, I'll just put a placeholder variable here.
        refresh_token = "your-oauth-flow-needs-to-set-this"

        # You should encrypt the refresh token before returning it
        encrypted_refresh_token = encrypt_refresh_token(refresh_token)

        user_info = {
            "email": idinfo['email'],
            "name": idinfo.get('name'),
            "picture": idinfo.get('picture'),
            "google_id": idinfo['sub'],
            "refresh_token": encrypted_refresh_token,
        }
        return user_info
    except ValueError as error:
        # Handle the error appropriately
        return None


