package de.effigenix.application.masterdata.productcategory;

import de.effigenix.domain.masterdata.article.ArticleRepository;
import de.effigenix.domain.masterdata.productcategory.ProductCategory;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryError;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryId;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

import static de.effigenix.shared.common.Result.*;

public class DeleteProductCategory {

    private final ProductCategoryRepository categoryRepository;
    private final ArticleRepository articleRepository;
    private final UnitOfWork unitOfWork;

    public DeleteProductCategory(ProductCategoryRepository categoryRepository, ArticleRepository articleRepository, UnitOfWork unitOfWork) {
        this.categoryRepository = categoryRepository;
        this.articleRepository = articleRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<ProductCategoryError, Void> execute(ProductCategoryId categoryId, ActorId performedBy) {
        ProductCategory category;
        switch (categoryRepository.findById(categoryId)) {
            case Failure(var err) ->
                { return Result.failure(new ProductCategoryError.RepositoryFailure(err.message())); }
            case Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new ProductCategoryError.CategoryNotFound(categoryId));
                }
                category = opt.get();
            }
        }

        return unitOfWork.executeAtomically(() -> {
            switch (articleRepository.findByCategory(categoryId)) {
                case Failure(var err) ->
                    { return Result.failure(new ProductCategoryError.RepositoryFailure(err.message())); }
                case Success(var articles) -> {
                    if (!articles.isEmpty()) {
                        return Result.failure(new ProductCategoryError.CategoryInUse(categoryId));
                    }
                }
            }

            switch (categoryRepository.delete(category)) {
                case Failure(var err) ->
                    { return Result.failure(new ProductCategoryError.RepositoryFailure(err.message())); }
                case Success(var ignored) -> { }
            }

            return Result.success(null);
        });
    }
}
