package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.RemoveStockBatchCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.Quantity;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.common.UnitOfMeasure;
import de.effigenix.shared.persistence.UnitOfWork;

import java.math.BigDecimal;

public class RemoveStockBatch {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<StockError, Void> execute(RemoveStockBatchCommand cmd) {
        // 1. Stock laden
        Stock stock;
        switch (stockRepository.findById(StockId.of(cmd.stockId()))) {
            case Result.Failure(var err) ->
                { return Result.failure(new StockError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new StockError.StockNotFound(cmd.stockId()));
                }
                stock = opt.get();
            }
        }

        // 2. Quantity aus Command-Strings bauen
        Quantity quantity;
        try {
            BigDecimal amount = new BigDecimal(cmd.quantityAmount());
            UnitOfMeasure uom;
            try {
                uom = UnitOfMeasure.valueOf(cmd.quantityUnit());
            } catch (IllegalArgumentException | NullPointerException e) {
                return Result.failure(new StockError.InvalidQuantity("Invalid unit: " + cmd.quantityUnit()));
            }
            switch (Quantity.of(amount, uom)) {
                case Result.Failure(var err) ->
                    { return Result.failure(new StockError.InvalidQuantity(err.message())); }
                case Result.Success(var val) -> quantity = val;
            }
        } catch (NumberFormatException | NullPointerException e) {
            return Result.failure(new StockError.InvalidQuantity(
                    "Invalid quantity amount: " + cmd.quantityAmount()));
        }

        // 3. Entnahme durchführen (Domain validiert)
        switch (stock.removeBatch(StockBatchId.of(cmd.batchId()), quantity)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 4. Stock speichern
        return unitOfWork.executeAtomically(() -> {
            switch (stockRepository.save(stock)) {
                case Result.Failure(var err) ->
                    { return Result.failure(new StockError.RepositoryFailure(err.message())); }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(null);
        });
    }
}
