from boss.interactor.insert_or_update_users.dto import InsertOrUpdateUsersRequest
from boss.model import User
from boss.model.repository import UserRepository
from boss_api.shared.exception import MissingMandatoryField
from .._BaseInteractor import BaseInteractor


class InsertOrUpdateUsersInteractor(BaseInteractor):

    def __init__(
        self,
        user_repository: UserRepository,
    ) -> None:

        self.user_repository = user_repository

    def execute(
        self,
        request: InsertOrUpdateUsersRequest,
    ) -> None:

        for user in request.users_to_insert_or_update:
            self._validate_mandatory_user_fields(user=user)

        self.user_repository.insert_or_update_users(users=request.users_to_insert_or_update)

    def _validate_mandatory_user_fields(
        self,
        user: User,
    ) -> None:

        existing_user_data = self.user_repository.get_user_by_id(user_id=user.user_id)
        mandatory_user_fields = self.user_repository.get_mandatory_user_fields()

        if existing_user_data:
            for field in mandatory_user_fields:
                if getattr(user, field) is None:
                    setattr(user, field, getattr(existing_user_data, field))
        else:
            for field in mandatory_user_fields:
                if getattr(user, field) is None:
                    exception = MissingMandatoryField()
                    exception.message = f"Mandatory field '{field}' cannot be None for a new user."
                    raise exception
