package de.effigenix.application.masterdata.productcategory;

import de.effigenix.application.masterdata.productcategory.command.UpdateProductCategoryCommand;
import de.effigenix.domain.masterdata.productcategory.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class UpdateProductCategory {

    private final ProductCategoryRepository categoryRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<ProductCategoryError, ProductCategory> execute(UpdateProductCategoryCommand cmd, ActorId performedBy) {
        var categoryId = ProductCategoryId.of(cmd.categoryId());

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

        var draft = new ProductCategoryUpdateDraft(cmd.name(), cmd.description());
        switch (category.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        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);
        });
    }
}
