package de.effigenix.application.inventory;

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

public class ReserveStock {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<StockError, Reservation> execute(ReserveStockCommand cmd) {
        // 1. Stock laden
        if (cmd.stockId() == null || cmd.stockId().isBlank()) {
            return Result.failure(new StockError.StockNotFound("null"));
        }

        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. Draft erstellen
        var draft = new ReservationDraft(
                cmd.referenceType(), cmd.referenceId(),
                cmd.quantityAmount(), cmd.quantityUnit(),
                cmd.priority()
        );

        // 3. Domain-Methode aufrufen
        Reservation reservation;
        switch (stock.reserve(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> reservation = val;
        }

        // 4. 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(reservation);
        });
    }
}
