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

    async def run(
        self,
        auth_code: str,
    ):
        tokens = await self.authenticator.get_token(auth_code)
        username = tokens.userinfo["preferred_username"]
        if username not in self.s.allowed_users:
            raise ValueError(f"User {username} is not allowed to use this bot")
        user = User(user=username, external_auth={"twitch": tokens.model_dump()})
        if await self.user_repo.get_by_user(user.user):
            await self.user_repo.update(user)
        else:
            await self.user_repo.create(user)
        return user.encode()
