import uuid

from pydantic import BaseModel

from huesoporro.models import User
from huesoporro.settings import Settings
from huesoporro.svc.users_svcs import (
    CreateUserSvc,
    GetTwitchAuthByAuthCodeSvc,
    GetUserByUsernameSvc,
    UpdateUserSvc,
)


class AuthenticateUserAction(BaseModel):
    get_tokens_by_auth_code_svc: GetTwitchAuthByAuthCodeSvc
    get_user_by_username_svc: GetUserByUsernameSvc
    create_user_svc: CreateUserSvc
    update_user_svc: UpdateUserSvc
    s: Settings

    async def run(
        self,
        auth_code: str,
    ) -> User:
        auth = await self.get_tokens_by_auth_code_svc.run(auth_code=auth_code)
        username = auth.userinfo["preferred_username"]
        user = await self.get_user_by_username_svc.run(username=username)
        if user:
            user.external_auth = {"twitch": auth}
            await self.update_user_svc.run(user)
            return user
        user = User(
            id=uuid.uuid4(),
            username=username,
            external_auth={"twitch": auth},
        )
        return await self.create_user_svc.run(user=user)
