package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.CreateStockCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.RepositoryError;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;

public class CreateStock {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

    public CreateStock(StockRepository stockRepository, UnitOfWork unitOfWork) {
        this.stockRepository = stockRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<StockError, Stock> execute(CreateStockCommand cmd) {
        // 1. Draft aus Command bauen (kein VO-Wissen im Use Case)
        var draft = new StockDraft(
                cmd.articleId(), cmd.storageLocationId(),
                cmd.minimumLevelAmount(), cmd.minimumLevelUnit(),
                cmd.minimumShelfLifeDays()
        );

        // 2. Aggregate erzeugen (validiert intern)
        Stock stock;
        switch (Stock.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> stock = val;
        }

        // 3. Uniqueness-Check (Application-Concern: braucht Repository)
        switch (stockRepository.existsByArticleIdAndStorageLocationId(stock.articleId(), stock.storageLocationId())) {
            case Result.Failure(var err) ->
                    { return Result.failure(new StockError.RepositoryFailure(err.message())); }
            case Result.Success(var exists) -> {
                if (exists) {
                    return Result.failure(new StockError.DuplicateStock(
                            cmd.articleId(), cmd.storageLocationId()));
                }
            }
        }

        // 4. Speichern (Race-Condition-Schutz: DuplicateEntry → DuplicateStock)
        return unitOfWork.executeAtomically(() -> {
            switch (stockRepository.save(stock)) {
                case Result.Failure(var err) -> {
                    if (err instanceof RepositoryError.DuplicateEntry) {
                        return Result.failure(new StockError.DuplicateStock(
                                cmd.articleId(), cmd.storageLocationId()));
                    }
                    return Result.failure(new StockError.RepositoryFailure(err.message()));
                }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(stock);
        });
    }
}
