from typing import List, Optional

from staff.headcounts.headcounts_credit_management.use_cases import dto
from staff.headcounts.headcounts_credit_management.use_cases.errors import AccessDeniedError
from staff.headcounts.headcounts_credit_management.use_cases.interfaces import (
    PermissionsInterface,
    RepositoryInterface,
    Startrek,
    Workflows,
)


class CreateUseCase:
    application_id: Optional[int] = None

    def __init__(
        self,
        permissions: PermissionsInterface,
        workflows: Workflows,
        repository: RepositoryInterface,
        startrek: Startrek,
    ):
        self._permissions = permissions
        self._workflows = workflows
        self._repository = repository
        self._startrek = startrek

    def has_rights(self, credit_repayment_request: dto.CreateCreditRepaymentRequest) -> bool:
        budget_position_ids: List[int] = []
        for row in credit_repayment_request.rows:
            budget_position_ids.extend((row.credit_budget_position_id, row.repayment_budget_position_id))
        return self._permissions.can_create_applications(budget_position_ids)

    def create(self, credit_repayment_request: dto.CreateCreditRepaymentRequest) -> None:
        if not self.has_rights(credit_repayment_request):
            raise AccessDeniedError

        self.application_id = self._repository.save(credit_repayment_request)
        credit_repayment = self._repository.get_by_id(self.application_id)

        self._workflows.create_workflow(credit_repayment)
