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 RefreshUserJwtAction(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, user: User) -> User | None:
        """Return None if the user has a valid token, otherwise refresh it and return the new token"""
        if await self.is_valid_token_svc.run(user=user):
            return None

        user = await self.refresh_token_svc.run(user=user)
        return await self.update_user_svc.run(user=user)
