package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.UnblockStockBatchCommand;
import de.effigenix.application.usermanagement.AuditEvent;
import de.effigenix.application.usermanagement.AuditLogger;
import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

import java.time.LocalDate;

public class UnblockStockBatch {

    private final StockRepository stockRepository;
    private final AuditLogger auditLogger;
    private final UnitOfWork unitOfWork;

    public UnblockStockBatch(StockRepository stockRepository, AuditLogger auditLogger, UnitOfWork unitOfWork) {
        this.stockRepository = stockRepository;
        this.auditLogger = auditLogger;
        this.unitOfWork = unitOfWork;
    }

    public Result<StockError, Void> execute(UnblockStockBatchCommand cmd, ActorId performedBy) {
        // 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. Batch entsperren (Domain validiert)
        switch (stock.unblockBatch(StockBatchId.of(cmd.batchId()), LocalDate.now())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. 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) -> { }
            }
            auditLogger.log(AuditEvent.STOCK_BATCH_UNBLOCKED, cmd.batchId(), performedBy);
            return Result.success(null);
        });
    }
}
