from flask import Blueprint, abort

from src.lib.account import (
    is_logged_in,
    load_account,
)
from src.lib.api import create_api_v2_client_error_response, TDAPIError

from .administrator import administrator_bp

account_bp = Blueprint("account", __name__, url_prefix="/account")


# check credentials for all requests for this blueprint
# so the subsequent handlers wouldn't need to check it again
@account_bp.before_request
def check_auth():
    if not is_logged_in():
        response = create_api_v2_client_error_response(
            TDAPIError(type="api_account_not_authenticated", message="Account not authenticated."), 401
        )
        abort(response)

    account = load_account()

    if not account:
        response = create_api_v2_client_error_response(
            TDAPIError(type="api_account_not_authenticated", message="Account not authenticated."), 401
        )
        abort(response)


account_bp.register_blueprint(administrator_bp)
