"""This module contains endpoints for operations related to users."""

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from todo.database.engine import get_db
from todo.schemas import users as userschema
from todo.crud import users as usercrud
from todo.utils.exceptions import NotFoundException, InvalidFilterParameterException
from todo.utils.exceptions import create_exception_dict as fmt
from todo.dependencies.users import UserSortablePaginationParams


router = APIRouter(
    prefix="/users",
    tags=["users"]
)

tag_metadata = {
    "name": "users",
    "description": "Operations related to users."
}


@router.post("/", response_model=userschema.User)
def create_user(user: userschema.UserCreate, db: Session = Depends(get_db)):
    try:
        # An exception is expected here, because we need to check if a user with this email is already registered
        usercrud.read_user_by_email(db, email=user.email)
        raise HTTPException(400, "A user with this email address is already registered.")
    except NotFoundException:
        return usercrud.create_user(db=db, user=user)


@router.get("/{id}", response_model=userschema.User)
def read_user(id: int, db: Session = Depends(get_db)):
    try:
        return usercrud.read_user(db=db, id=id)
    except NotFoundException as e:
        raise HTTPException(404, fmt(str(e)))


@router.get("/", response_model=list[userschema.User])
def read_users(
        commons: Annotated[UserSortablePaginationParams, Depends(UserSortablePaginationParams)],
        db: Session = Depends(get_db)
    ):
    try:
        return usercrud.read_users(
            db=db,
            skip=commons.skip,
            limit=commons.limit,
            sortby=commons.sortby,
            sortorder=commons.sortorder
        )
    except InvalidFilterParameterException as e:
        raise HTTPException(400, fmt(str(e)))


@router.get("/total/", response_model=dict[str, int])
def read_users_count(db: Session = Depends(get_db)):
    return {"total": usercrud.read_users_count(db=db)}


@router.patch("/{id}", response_model=userschema.User)
def update_user(id: int, user: userschema.UserUpdate, db: Session = Depends(get_db)):
    try:
        return usercrud.update_user(db=db, user=user, id=id)
    except NotFoundException as e:
        raise HTTPException(404, fmt(str(e)))


@router.delete("/{id}", response_model=userschema.User)
def delete_user(id: int, db: Session = Depends(get_db)):
    try:
        return usercrud.delete_user(db=db, id=id)
    except NotFoundException as e:
        raise HTTPException(404, fmt(str(e)))
