import secrets

from litestar import MediaType, get
from litestar.datastructures.cookie import Cookie
from litestar.response import Redirect, Template

from huesoporro.actions.users.authenticate_user import AuthenticateUserAction
from huesoporro.settings import Settings


@get(path="/o/code")
async def get_code(code: str, authenticate_action: AuthenticateUserAction) -> Redirect:
    user = await authenticate_action.run(code)
    token = user.encode()
    return Redirect(
        "/",
        cookies=[
            Cookie(
                key="huesoporroAuth",
                value=token,
                expires=604800,  # 1 week
            )
        ],
    )


@get(
    "/login",
    media_type=MediaType.HTML,
)
async def login(s: Settings) -> Template:
    scopes = "+".join(s.twitch_scopes)
    return Template(
        "login.html",
        context={
            "twitch_login_url": "https://id.twitch.tv/oauth2/authorize?response_type=code"
            f"&client_id={s.twitch_client_id}"
            f"&redirect_uri={s.server_hostname}o/code"
            f"&scope={scopes}"
            f"&state={secrets.token_urlsafe(32)}"
        },
    )
