from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
import httpx
import logging
from app.common.config import settings
from app.common.service_utils import get_service_url

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# OAuth2 scheme for token authentication
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/token")

async def validate_token(token: str = Depends(oauth2_scheme)):
    """
    Validate the token by making a request to the auth service.
    Returns the user information if the token is valid.
    """
    auth_service_url = get_service_url("auth")
    validate_url = f"{auth_service_url}/api/v1/validate-token"
    logger.info(f"Attempting to validate token at: {validate_url}")
    
    try:
        # Disable SSL verification for development
        async with httpx.AsyncClient(timeout=10.0, verify=False) as client:
            logger.info("Sending request to auth service...")
            response = await client.post(
                validate_url,
                headers={"Authorization": f"Bearer {token}"}
            )
            
            logger.info(f"Auth service response status: {response.status_code}")
            
            if response.status_code == 200:
                user_data = response.json()["user"]
                logger.info(f"Token validated successfully for user: {user_data.get('email', 'unknown')}")
                return user_data
            
            logger.error(f"Auth service returned error: {response.status_code} - {response.text}")
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail=f"Invalid authentication credentials: {response.text}",
                headers={"WWW-Authenticate": "Bearer"},
            )
    except httpx.ConnectError as e:
        logger.error(f"Connection error to auth service: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=f"Auth service unavailable: {str(e)}",
        )
    except httpx.TimeoutException as e:
        logger.error(f"Timeout connecting to auth service: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT,
            detail=f"Auth service timeout: {str(e)}",
        )
    except Exception as e:
        logger.error(f"Unexpected error validating token: {str(e)}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Authentication error: {str(e)}",
        ) 