from flask import Blueprint, abort, request

from src.lib.api import (
    create_api_v2_invalid_body_error_response,
    create_api_v2_error_response,
    TDAPIRequestBody,
    APIV2_REQUEST_BODY_TYPE,
    TDAPIError,
)

from .file import file_bp
from .account import account_bp

v2api_bp = Blueprint("v2", __name__, url_prefix="/v2")

methods_with_body = ("POST", "PUT", "PATH", "DELETE")


# validate body of request for methods which support bodies
@v2api_bp.before_request
def check_api_request():
    method = request.method

    if method not in methods_with_body:
        return

    body: TDAPIRequestBody = request.get_json()

    if not (isinstance(body, dict)):
        abort(create_api_v2_invalid_body_error_response())

    type = body.get("type")

    if not type or type != APIV2_REQUEST_BODY_TYPE:
        abort(create_api_v2_invalid_body_error_response())


@v2api_bp.errorhandler(500)
def handle_server_error(error: Exception):
    """
    TODO: proper logging
    """
    responseError = TDAPIError(type="server_error", message="Unknown error.")

    return create_api_v2_error_response(responseError, 500)


v2api_bp.register_blueprint(file_bp)
v2api_bp.register_blueprint(account_bp)
