import os
import httpx
from dotenv import load_dotenv
from models.auth_user_modal import User
from database import SessionLocal

load_dotenv()

CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
REDIRECT_URI = os.getenv("GOOGLE_REDIRECT_URI")


async def get_google_user(code: str):
    token_url = "https://oauth2.googleapis.com/token"
    token_data = {
        "code": code,
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "redirect_uri": REDIRECT_URI,
        "grant_type": "authorization_code",
    }

    try:
        async with httpx.AsyncClient() as client:
            headers = {"Content-Type": "application/x-www-form-urlencoded"}
            token_res = await client.post(token_url, data=token_data, headers=headers)
            token_res.raise_for_status()
            tokens = token_res.json()

            # Use access token to fetch user profile
            user_info_res = await client.get(
                "https://www.googleapis.com/oauth2/v2/userinfo",
                headers={"Authorization": f"Bearer {tokens['access_token']}"}
            )
            user_info_res.raise_for_status()
            user_data = user_info_res.json()

            print("✅ Google User Data Received:", user_data)

            # Connect to database
            db = SessionLocal()
            try:
                # Check if user already exists
                existing_user = db.query(User).filter(User.google_id == user_data["id"]).first()

                if existing_user:
                    print("ℹ️ User already exists in DB:", existing_user.email)
                else:
                    # Insert new user
                    new_user = User(
                        google_id=user_data["id"],
                        name=user_data["name"],
                        email=user_data["email"],
                        picture=user_data["picture"],
                    )
                    db.add(new_user)
                    db.commit()
                    db.refresh(new_user)
                    print("✅ New user added to DB:", new_user.email)

            finally:
                db.close()

            return user_data

    except httpx.HTTPStatusError as e:
        print("❌ Token exchange failed:", e.response.text)
        return {"error": "Google OAuth failed", "details": e.response.text}
