from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from src.schemas.user import UserCreate, UserLogin, ForgotPassword, ResetPassword, UserResponse
from src.services.user_service import (
    create_user, login_user, initiate_forgot_password,
    handle_password_reset, verify_email_otp
)
from src.db.session import get_db
from src.utils.jwt_utils import get_current_user
from src.utils.response_utils import create_response
from src.utils.exceptions import PasswordValidationException
from src.schemas.custom import CustomResponse
router = APIRouter()

@router.post("/signup",response_model=CustomResponse)
async def signup(user_create: UserCreate, request: Request, db: Session = Depends(get_db)):
    try:
        user_response = await create_user(db=db, user_create=user_create, request=request)
        return CustomResponse(
                hasError=False,
                error=None,
                message="User signed up successfully.",
                data=user_response.dict()
            )

    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except HTTPException as e:
        raise e  # Re-raise known HTTPExceptions to keep their status codes
    except Exception as e:
        # Handle general exceptions and provide better debugging info
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"An unexpected error occurred: {str(e)}")


@router.post("/verify-email",response_model=CustomResponse)
async def verify_email(email: str, otp: str, db: Session = Depends(get_db)):
    try:
        await verify_email_otp(db=db, email=email, otp=otp)
        return create_response(message="Email verified successfully.")
    except ValueError as e:
        # Triggered by invalid OTP or user not found
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=create_response(error=str(e)))
    except Exception as e:
        # Trigger the global exception handler
        raise e




@router.post("/signin", response_model=CustomResponse)
async def signin(user_login: UserLogin, db: Session = Depends(get_db)):
    try:
        result = await login_user(db, user_login)
        if not result:
            raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")

        # Extract token and user details from the result
        token = result.get("token")
        email = result.get("email")
        first_name = result.get("first_name")
        last_name = result.get("last_name")
        is_verified = result.get("is_verified")

        return CustomResponse(
            hasError=False,
            error=None,
            data={
                "access_token": token,
                "token_type": "bearer",
                "email": email,
                "first_name": first_name,
                "last_name": last_name,
                "is_verified": is_verified
            },
            message="Sign in successful."
        )

    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except HTTPException as e:
        raise e  # Re-raise known HTTPExceptions to keep their status codes
    except Exception as e:
        # Handle general exceptions and provide better debugging info
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=f"An unexpected error occurred: {str(e)}")



@router.post("/forgot-password")
async def forgot_password(forgot_password: ForgotPassword, request: Request, db: Session = Depends(get_db)):
    try:
        await initiate_forgot_password(db, forgot_password.email, request=request)
        return create_response(message="If your email is registered, you will receive instructions to reset your password.")
    except ValueError as e:
        # Handle specific error (e.g., user not found)
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=create_response(error=str(e)))
    except Exception as e:
        # Handle unexpected errors
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=create_response(error=str(e)))


@router.post("/reset-password")
async def reset_password_endpoint(reset_password: ResetPassword, request: Request, db: Session = Depends(get_db)):
    try:
        # Call the utility function to handle the password reset
        await handle_password_reset(db, reset_password, request=request)
        return create_response(message="Password reset successful.")
    except ValueError as e:
        # Handle specific error (e.g., invalid or expired token)
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=create_response(error=str(e)))
    except Exception as e:
        # Handle unexpected errors
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=create_response(error=str(e)))



@router.get("/me", response_model=UserResponse)
async def get_me(current_user: UserResponse = Depends(get_current_user)):
    return create_response(data=current_user, message="User profile fetched successfully.")
