from src.domain.interfaces.user_repository import UserRepository
from src.core.security import verify_password, create_access_token
from src.core.exceptions import InvalidCredentialsException, UserNotFoundException
from src.core.logger import get_logger
from src.core.rbac.user_type_map import resolve_role

logger = get_logger()

class AuthenticateUserUseCase:
    def __init__(self, user_repo: UserRepository):
        self.user_repo = user_repo

    def execute(self, email: str, base_password: str) -> str:
        logger.debug(f"Attempting to authenticate user: {email}")
        user = self.user_repo.get_user_by_email(email)
        
        if not user:
            logger.info(f"Authentication failed: User {email} not found")
            raise InvalidCredentialsException()

        if not verify_password(base_password, user.hashed_password):
            logger.info(f"Authentication failed: Invalid password for {email}")
            raise InvalidCredentialsException()

        # Resolve RBAC role from legacy user_type and embed it in the JWT
        role = resolve_role(user.user_type)
        token = create_access_token(data={
            "sub": user.email,
            "user_id": user.id,
            "role": role,          # <-- RBAC role embedded here
            "user_type": user.user_type,
        })
        logger.info(f"Authentication successful for user: {email} | role: {role}")
        return token

