"""Module to handle the register process."""

import re
import uuid
from flask import Blueprint, request, jsonify
from custom_functions.database.user_db import add_user

register_bp = Blueprint("register_bp", __name__)

USERNAME_REGEX = re.compile(r"^[A-Za-z0-9_-]+$")
PASSWORD_REGEX = re.compile(r"^\S+$")


@register_bp.route("/register", methods=["POST"])
def register():
    """Handle the register process."""
    data = request.get_json()
    if data is None:
        return jsonify({"error": "Invalid or missing JSON in request body."}), 400

    # Check required fields
    for required_field in ["username", "password"]:
        if required_field not in data:
            return jsonify({"error": f"Missing required field: {required_field}"}), 400

    username = data["username"].lower()
    password = data["password"]
    api_key = str(uuid.uuid4())

    # Length checks
    if not (3 <= len(username) <= 32):
        return jsonify({"error": "Username must be 3-32 characters."}), 400
    if not (8 <= len(password) <= 128):
        return jsonify({"error": "Password must be 8-128 characters."}), 400

    # Validate username and password
    if not USERNAME_REGEX.fullmatch(username):
        return (
            jsonify(
                {
                    "error": "Invalid username. Only letters, numbers, hyphens, and underscores are allowed."
                }
            ),
            400,
        )

    if not PASSWORD_REGEX.fullmatch(password):
        return jsonify({"error": "Invalid password. Spaces are not allowed."}), 400

    # Attempt to add user
    if add_user(username, password, api_key):
        return (
            jsonify({"message": "User successfully registered!", "api_key": api_key}),
            201,
        )
    return jsonify({"error": "User already exists!"}), 409
