from loguru import logger
from pydantic import BaseModel

from src.huesoporro.infra.authenticator import TwitchAuthenticator
from src.huesoporro.infra.repos import UserRepo
from src.huesoporro.models import User
from src.huesoporro.settings import Settings


class GetUserByJWTAction(BaseModel):
    user_repo: UserRepo
    authenticator: TwitchAuthenticator
    s: Settings

    async def run(
        self,
        jwt_token: str,
    ) -> User:
        user_data = User.decode(jwt_token)
        username = user_data["user"]
        user = await self.user_repo.get_by_user(username)
        if not user:
            raise ValueError(f"User {username} not found")
        is_valid = await self.authenticator.token_is_valid(
            user.external_auth["twitch"]["access_token"]
        )
        logger.info(f"Token {user} is valid: {is_valid}")
        if not is_valid:
            logger.info(f"Refreshing token for user {user}")
            new_tokens = await self.authenticator.refresh_token(
                user.external_auth["twitch"]["refresh_token"]
            )
            user.external_auth["twitch"]["access_token"] = new_tokens["access_token"]  # type: ignore[index]
            user.external_auth["twitch"]["refresh_token"] = new_tokens["refresh_token"]  # type: ignore[index]
            await self.user_repo.update(user)
            return user

        return user
