from fastapi import Depends, HTTPException, status, Request
from fastapi.routing import APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.security import OAuth2PasswordBearer
from fastapi.responses import RedirectResponse
from supabase import Client
from app.config import settings
from jose import JWTError, jwt
import os
from app.routers.helpers import get_supabase, get_current_user_required, get_current_user_optional
from app.schemas.user import UserCreate, UserLogin, UserOut
from app.schemas.token import RefreshResponse, RefreshToken

router = APIRouter(tags=["auth"])

@router.get("/login/google")
async def login_with_google(supabase: Client = Depends(get_supabase)):
    try:
        response = supabase.auth.sign_in_with_oauth({
            "provider": "google",
            "options": {
                "redirect_to": "http://localhost:8000/auth/callback"
            }
        })
        return {"auth_url": response.url}
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.get("/callback")
async def google_callback(request: Request, supabase: Client = Depends(get_supabase)):
    code = request.query_params.get("code")
    if not code:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing authorization code")

    supabase.auth.exchange_code_for_session({"auth_code": code})
    return RedirectResponse(url="http://localhost:5173")

@router.get("/users/me")
async def get_me(
    user = Depends(get_current_user_required),
):
    try:
        return jsonable_encoder(user)
    except IndexError:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="User not found in database"
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )

@router.post("/refresh", response_model=RefreshResponse)
async def refresh_token(refresh_request: RefreshToken, supabase: Client = Depends(get_supabase)):
    """Refresh the access token using a valid refresh token."""
    try:
        # Validate the refresh token and get new tokens
        response = supabase.auth.refresh_session(refresh_request.refresh_token)
        
        # Extract user data
        user_data = {
            "id": response.user.id,
            "email": response.user.email,
            "first_name": response.user.user_metadata.get("first_name", "Unknown"),
            "last_name": response.user.user_metadata.get("last_name", "Unknown"),
            "business_name": response.user.user_metadata.get("business_name", "Unknown")
        }
        
        # Return the new tokens and user data
        return {
            "access_token": response.session.access_token,
            "refresh_token": response.session.refresh_token,
            "expires_at": int(response.session.expires_at),
            "user": user_data
        }
    except Exception as e:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=f"Failed to refresh token: {str(e)}")
    