import json

from django.http import HttpRequest, HttpResponse, JsonResponse, HttpResponseNotFound
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from staff.lib.decorators import auth_by_tvm_only

from staff.budget_position.forms.tableflow_validation_forms import (
    TableflowBaseValidationForm,
    BonusGroupRulesValidationForm,
    RewardCategoryRulesValidationForm,
    ReviewGroupRulesValidationForm,
    RewardRulesValidationForm,
    BonusRulesValidationForm,
    ReviewRulesValidationForm,
)


@csrf_exempt
@require_POST
@auth_by_tvm_only(['table_flow'])
def validate_rules(request: HttpRequest, rule: str) -> HttpResponse:
    rules = json.loads(request.body)
    forms = {
        'bonus_group_rules': BonusGroupRulesValidationForm,
        'reward_category_rules': RewardCategoryRulesValidationForm,
        'review_group_rules': ReviewGroupRulesValidationForm,
        'reward_rules': RewardRulesValidationForm,
        'bonus_rules': BonusRulesValidationForm,
        'review_rules': ReviewRulesValidationForm,
    }

    form_cls = forms.get(rule)

    if not form_cls:
        return HttpResponseNotFound()

    form: TableflowBaseValidationForm = form_cls(data=rules)
    if form.is_valid():
        return JsonResponse(data={})

    error_data = {'messages': form.human_readable_errors()}
    return JsonResponse(data=error_data, status=400)
