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 RefreshAction(BaseModel):
    user_repo: UserRepo
    authenticator: TwitchAuthenticator
    s: Settings

    async def run(self, user: User):
        is_valid = await self.authenticator.token_is_valid(
            user.external_auth["twitch"]["access_token"]
        )

        if not is_valid:
            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.encode()
        return None
