from loguru import logger
from pydantic import BaseModel

from huesoporro.models import User
from huesoporro.settings import Settings
from huesoporro.svc.users_svcs import (
    GetUserByUsernameSvc,
    IsValidTokenSvc,
    RefreshTokenSvc,
    UpdateUserSvc,
)


class GetUserByJWTAction(BaseModel):
    get_user_by_username_svc: GetUserByUsernameSvc
    update_user_svc: UpdateUserSvc
    refresh_token_svc: RefreshTokenSvc
    is_valid_token_svc: IsValidTokenSvc
    s: Settings

    async def run(
        self,
        jwt_token: str,
    ) -> User | None:
        user_data = User.decode(jwt_token, settings=self.s)
        username = user_data["username"]
        user = await self.get_user_by_username_svc.run(username=username)
        if not user:
            raise ValueError(f"User {username} not found")
        if await self.is_valid_token_svc.run(user=user):
            logger.info(
                f"User {username} has a correct twitch authentication token, returning user"
            )
            return user

        logger.info(
            f"User {username} has an invalid twitch authentication token, refreshing it"
        )
        user = await self.refresh_token_svc.run(user=user)
        return await self.update_user_svc.run(user=user)
