from flask import request

from src.lib.pagination import create_pagination
from src.lib.api import create_api_v2_response, create_api_v2_client_error_response, TDAPIError
from src.lib.administrator import count_accounts, get_accounts


def get_accounts_count():
    name = request.args.get("name")
    role = request.args.get("role")

    if name:
        name = name.strip()

    count = count_accounts(role, name)
    response = create_api_v2_response(count)

    return response


def get_account_list(page: str):
    current_page = int(page)
    name = request.args.get("name")
    role = request.args.get("role")

    if name:
        name = name.strip()

    if current_page < 1:
        return create_api_v2_client_error_response(
            TDAPIError(type="invalid_page", message="Page number must be positive.")
        )

    count = count_accounts(role, name)
    pagination = create_pagination(count, current_page)

    if current_page > pagination["total_pages"]:
        return create_api_v2_client_error_response(
            TDAPIError(type="invalid_page", message="Page number must not be higher than total pages.")
        )

    accounts = get_accounts(pagination, role, name)
    response = create_api_v2_response(accounts)

    return response
