from fastapi import APIRouter, HTTPException
from setech.utils import get_logger

from service.api.dependencies import QueryParams
from service.core.exceptions import InvalidEmail
from service.crud.user import UserMe, UserPublic, UserRegister, get_user_by_username, get_users, register_user

user_router = router = APIRouter()
logger = get_logger("api")


@router.get("/list")
async def list_users_view(_params: QueryParams) -> list[UserPublic] | None:
    return await get_users(_params)


@router.post("/register")
async def register_user_view(data: UserRegister) -> UserMe | None:
    try:
        if await get_user_by_username(username=data.email):
            raise HTTPException(400, "Given email is already registered!")
    except InvalidEmail as e:
        logger.warning(f"Attempting to register with invalid email: '{data.email}'")
        raise HTTPException(400, str(e))
    logger.info(f"Creating user with email: '{data.email}'")
    user = await register_user(data)
    return UserMe(id=user.id, username=user.username, email=user.email, is_superuser=user.is_superuser)
