package de.effigenix.application.masterdata;

import de.effigenix.application.masterdata.command.CreateProductCategoryCommand;
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 CreateProductCategory {

    private final ProductCategoryRepository categoryRepository;

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

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

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