"""Module to handle the login process."""

from flask import Blueprint, request, jsonify, session
from custom_functions.database.user_db import verify_user

login_bp = Blueprint(
    "login_bp",
    __name__,
)


@login_bp.route("/login", methods=["POST"])
def login():
    """Handle the login process."""
    data = request.get_json()
    for required_field in ["username", "password"]:
        if required_field not in data:
            return (
                jsonify({"error": f"Missing required field: {required_field}"}),
                400,
            )

    if verify_user(data["username"], data["password"]):
        session["username"] = data[
            "username"
        ].lower()  # Stored securely in a signed cookie
        return jsonify({"message": "Successfully logged in!"})
    return jsonify({"error": "Invalid username or password!"}), 401


@login_bp.route("/login/status", methods=["POST"])
def login_status():
    """Check if the user is logged in."""
    username = session.get("username")
    return jsonify({"message": "True" if username else "False"})


@login_bp.route("/logout", methods=["POST"])
def logout():
    """Logout the user."""
    session.pop("username", None)
    return jsonify({"message": "Successfully logged out!"})
