package de.effigenix.application.masterdata.productcategory;

import de.effigenix.application.masterdata.productcategory.command.CreateProductCategoryCommand;
import de.effigenix.domain.masterdata.productcategory.ProductCategory;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryDraft;
import de.effigenix.domain.masterdata.productcategory.ProductCategoryError;
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;

public class CreateProductCategory {

    private final ProductCategoryRepository categoryRepository;
    private final UnitOfWork unitOfWork;

    public CreateProductCategory(ProductCategoryRepository categoryRepository, UnitOfWork unitOfWork) {
        this.categoryRepository = categoryRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<ProductCategoryError, ProductCategory> execute(CreateProductCategoryCommand cmd, ActorId performedBy) {
        var draft = new ProductCategoryDraft(cmd.name(), cmd.description());

        ProductCategory category;
        switch (ProductCategory.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> category = val;
        }

        switch (categoryRepository.existsByName(category.name())) {
            case Result.Failure(var err) ->
                { return Result.failure(new ProductCategoryError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new ProductCategoryError.CategoryNameAlreadyExists(cmd.name()));
                }
            }
        }

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