from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from starlette import status

from service.api.dependencies import LoggedInUser
from service.api.models.auth import Token
from service.core import security
from service.crud.user import UserMe, authenticate

auth_router = router = APIRouter()


@router.post("/access-token")
async def login_access_token(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]) -> Token:
    """
    OAuth2 compatible token login, get an access token for future requests
    """
    user = await authenticate(username=form_data.username, password=form_data.password)
    if not user:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect email and/or password")
    return Token(access_token=security.create_access_token(user.username))


@router.post("/test-token", response_model=UserMe)
async def test_token(current_user: LoggedInUser) -> UserMe:
    """
    Test access token
    """
    return UserMe(
        id=current_user.id,
        email=current_user.email,
        is_superuser=current_user.is_superuser,
        username=current_user.username,
    )
