from django.http import HttpRequest, JsonResponse, HttpResponse, HttpResponseForbidden

from staff.headcounts.permissions import Permissions

from staff.headcounts_history.forms import FilterForm
from staff.headcounts_history.models import DepartmentHeadcountSnapshot


def headcounts_history(request: HttpRequest, department_url: str) -> HttpResponse:
    permissions = Permissions(request.user.get_profile())
    if not permissions.has_access_to_department_url(department_url):
        return HttpResponseForbidden()

    form = FilterForm(request.GET)
    if not form.is_valid():
        return JsonResponse(data=form.errors_as_dict(), status=400)

    date_from = form.cleaned_data['date_from']
    date_to = form.cleaned_data['date_to']

    fields = (
        'id',
        'department_id',
        'department__url',
        'date_from',
        'date_to',
        'name',
        'name_en',
        'total_hc',
        'current_count',
        'offers',
        'current_balance',
        'vacancy_open',
        'vacancy_plan',
        'vacancy_plan_new',
        'vacancy_plan_replacement',
        'reserve_new',
        'crossheadcount',
        'replacement_to_working',
        'offers_for_working_replacement',
        'vacancy_open_for_working_replacement',
        'vacancy_plan_for_working_replacement',
        'overdraft_percents_with_child',
    )

    result = list(
        DepartmentHeadcountSnapshot.objects
        .filter(date_to__gte=date_from, date_from__lte=date_to, department__url=department_url)
        .values(*fields)
    )

    return JsonResponse(data={'snapshots': result})
