import traceback
from account.models import PhoneVerificationService

# как создавать ошибку
# raise Exception(API_ERROR_XXX, <related_obj>)


API_ERROR_INTERNAL_ERROR = (100, 'internal error')

API_ERROR_METHOD_NOT_FOUND = (200, 'method not found')
API_ERROR_MISSING_ARGUMENT = (201, 'missing argument')
API_ERROR_UNKNOWN_ARGUMENT = (202, 'unknown argument')
API_ERROR_INVALID_ARGUMENT_TYPE = (203, 'invalid argument type')

API_ERROR_TOKEN_CREATION = (500, 'token creation error')

API_ERROR_INVALID_LOGIN = (501, 'invalid login')
API_ERROR_INVALID_PASSWORD = (502, 'invalid password')
API_ERROR_INVALID_TOKEN = (503, 'invalid token')

# времненное решение, позже нужно будет заменить на конкретные ошибки
API_ERROR_USER_REGISTER = (510, 'user registration error')

API_ERROR_VALIDATION_INVALID_CODE = (520, 'invalid code')
API_ERROR_VALIDATION_MAX_ATTEMPTS = (521, 'max attempts')
API_ERROR_VALIDATION_CURRENTLY_VERIFIED = (522, 'currently phone is verified')
API_ERROR_VALIDATION_FAILED = (523, 'cannot be verified')
API_ERROR_VALIDATION_NOT_READY = (524, 'verification service not ready. call this method later')
API_ERROR_VALIDATION_NOT_FOUND = (525, 'verification service did not send code. call this method without \'code\'')
API_ERROR_VALIDATION_UNKNOWN = (526, 'unknown verification error')

API_ERROR_VALIDATION = {
    PhoneVerificationService.CHECK_PHONE_INVALID_CODE: API_ERROR_VALIDATION_INVALID_CODE,
    PhoneVerificationService.CHECK_PHONE_MAX_ATTEMPTS: API_ERROR_VALIDATION_MAX_ATTEMPTS,
    PhoneVerificationService.CHECK_PHONE_FAILED: API_ERROR_VALIDATION_FAILED,
    PhoneVerificationService.CHECK_PHONE_NOT_READY: API_ERROR_VALIDATION_NOT_READY,
    PhoneVerificationService.CHECK_PHONE_NOT_FOUND: API_ERROR_VALIDATION_NOT_FOUND,
}


def make_error_object(ex: Exception):
    try:
        if type(ex.args[0]) != tuple:
            raise Exception(API_ERROR_INTERNAL_ERROR)

        data = {
            "error": {
                "code": ex.args[0][0],
                "message": ex.args[0][1]
            }
        }

        if len(ex.args) >= 2:
            data["error"]["related"] = ex.args[1]

        return data
    except Exception:
        traceback.print_exc()
        return {
            "error": {
                "code": API_ERROR_INTERNAL_ERROR[0],
                "message": API_ERROR_INTERNAL_ERROR[1]
            }
        }
