package de.effigenix.application.inventory;

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

public class ReleaseReservation {

    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<StockError, Void> execute(ReleaseReservationCommand 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. Reservation freigeben
        switch (stock.releaseReservation(ReservationId.of(cmd.reservationId()))) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. 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);
        });
    }
}
