from staff.departments.models import DepartmentStaff, DepartmentRoles

from staff.lib.utils.qs_values import extract_related
from staff.lib.models.mptt import filter_by_heirarchy


def get_chief_for_dismissal(dismissal):
    chiefs = DepartmentStaff.objects.filter(
        role_id=DepartmentRoles.CHIEF.value,
    )
    chiefs = (
        filter_by_heirarchy(
            chiefs,
            [dismissal.department],
            by_children=False,
            filter_prefix='department__',
            include_self=True
        )
        .exclude(staff__login=dismissal.staff.login)
        .order_by('-department__lft')
        .values(
            'staff__login',
            'staff__first_name',
            'staff__last_name'
        )
    )

    return chiefs and extract_related(chiefs[0], 'staff') or None
