"""This module contains endpoints for operations related to user authentication."""

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

from todo.database.engine import get_db
from todo.utils.exceptions import NotFoundException, create_exception_dict as fmt
import todo.auth.auth as auth
from todo.crud.users import read_user_by_email_with_password
from todo.schemas.users import UserLogin as UserLoginSchema
from todo.schemas.auth import AuthResponseToken


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

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


@router.post("/login", response_model=AuthResponseToken)
def login(credentials: UserLoginSchema, db: Session = Depends(get_db)):
    """Returns a JWT for the user whose credentials were provided.

    The JWT can be submitted as a Bearer token on subsequent requests to authenticate
    the user.
    """

    try:
        user = read_user_by_email_with_password(db, credentials.email)
    except NotFoundException:
        raise HTTPException(401, fmt("Invalid email or password."))

    if not auth.AuthHandler().verify_password(credentials.password, user.password):
        raise HTTPException(401, fmt("Invalid email or password."))

    return AuthResponseToken(token=auth.AuthHandler().encode_token(user.id))
