package de.effigenix.application.masterdata;

import de.effigenix.application.masterdata.command.UpdateProductCategoryCommand;
import de.effigenix.domain.masterdata.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class UpdateProductCategory {

    private final ProductCategoryRepository categoryRepository;

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

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

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