from litestar import Request
from litestar.exceptions import HTTPException

from src.huesoporro.actions.authenticate import AuthenticateAction
from src.huesoporro.actions.get_user_by_jwt import GetUserByJWTAction
from src.huesoporro.infra.authenticator import TwitchAuthenticator
from src.huesoporro.infra.db import Database
from src.huesoporro.infra.repos import UserRepo
from src.huesoporro.models import User
from src.huesoporro.settings import Settings
from src.huesoporro.svc.get_chatbot_settings import ChatbotSettingsGetterSvc
from src.huesoporro.svc.get_sentences_svc import SentencesGetterSvc
from src.huesoporro.svc.store_settings import ChatbotSettingsStorerSvc


def get_settings() -> Settings:
    return Settings.get()


def get_authenticator(s: Settings) -> TwitchAuthenticator:
    return TwitchAuthenticator(s=s)


def get_db(s: Settings):
    return Database(s=s)


async def get_get_user_by_jwt_action(
    user_repo: UserRepo, authenticator: TwitchAuthenticator, s: Settings
):
    return GetUserByJWTAction(user_repo=user_repo, authenticator=authenticator, s=s)


async def authenticate(
    request: Request, get_user_by_jwt_action: GetUserByJWTAction
) -> User:
    token = request.query_params.get("huesoporro_token")
    if token:
        return await get_user_by_jwt_action.run(token)

    cookies = request.cookies.get("huesoporroAuth")
    if cookies:
        return await get_user_by_jwt_action.run(cookies)

    raise HTTPException(status_code=401, detail="Unauthorized")


async def get_chatbot_settings_svc(db: Database):
    return ChatbotSettingsGetterSvc(db=db)


async def store_chatbot_settings_svc(db: Database):
    return ChatbotSettingsStorerSvc(db=db)


async def get_sentences_svc(db: Database):
    return SentencesGetterSvc(db=db)


async def get_user_repo(s: Settings):
    return UserRepo(s=s)


async def get_authenticate_action(
    user_repo: UserRepo, authenticator: TwitchAuthenticator, s: Settings
):
    return AuthenticateAction(user_repo=user_repo, authenticator=authenticator, s=s)
