import logging
from typing import Optional

from staff.person.models import Staff

from staff.budget_position.workflow_service.use_cases import CreditManagementServiceInterface
from staff.budget_position.workflow_service.entities import WorkflowRepositoryInterface


logger = logging.getLogger(__name__)


class CreditManagementService(CreditManagementServiceInterface):
    def __init__(self, workflow_repository: WorkflowRepositoryInterface) -> None:
        self._repository = workflow_repository

    def notify_about_changes_for_application(
        self,
        credit_management_application_id: int,
        person_id: Optional[int],
    ) -> None:
        if self._repository.is_all_workflows_for_credit_repayment_is_cancelled(credit_management_application_id):
            logger.info(
                'All workflows for %s credit management application cancelled, notifying credit management service',
                credit_management_application_id,
            )
            self._on_all_workflows_cancelled(credit_management_application_id, person_id)
            return

        if self._repository.is_all_workflows_for_credit_repayment_not_in_pending(credit_management_application_id):
            logger.info(
                'All workflows for %s credit management application completed, notifying credit management service',
                credit_management_application_id,
            )
            self._on_all_workflows_pushed(credit_management_application_id)

    def _on_all_workflows_pushed(self, credit_management_application_id: int):
        # to avoid circular imports
        from staff.headcounts.headcounts_credit_management.use_cases import CloseUseCase
        from staff.headcounts.headcounts_credit_management.gateways import Repository

        use_case = CloseUseCase(Repository(None))
        use_case.close(credit_management_application_id)

    def _on_all_workflows_cancelled(self, credit_management_application_id: int, person_id: Optional[int]):
        # to avoid circular imports
        from staff.headcounts.headcounts_credit_management.use_cases import CancelUseCase
        from staff.headcounts.headcounts_credit_management.gateways import Repository

        person = Staff.objects.get(id=person_id)
        use_case = CancelUseCase(Repository(person))
        use_case.cancel(credit_management_application_id)
