from typing import List

from staff.departments.models import Department

from staff.headcounts.headcounts_summary.query_builder.query_params import HierarchyValues


class HierarchyPartQueryBuilder:
    def __init__(self, filters: List[HierarchyValues]) -> None:
        self._filters = filters

    @property
    def _department_table(self) -> str:
        return Department._meta.db_table

    def _static_part(self) -> str:
        return f'SELECT dep.id as id FROM {self._department_table} as dep'

    def _where_filter(self) -> str:
        if not self._filters:
            return 'WHERE TRUE'

        filters_expression = ' OR '.join(self._format_hierarchy_filters(self._filters))
        return f'WHERE {filters_expression}'

    def _format_hierarchy_filters(self, filters: List[HierarchyValues]) -> List[str]:
        return [
            f'(dep.tree_id = {it.tree_id} AND dep.lft >= {it.lft} AND dep.rght <= {it.rght})'
            for it in filters
        ]

    def build(self) -> str:
        return f'{self._static_part()} {self._where_filter()}'
