package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.CancelInventoryCountCommand;
import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

public class CancelInventoryCount {

    private final InventoryCountRepository inventoryCountRepository;
    private final AuthorizationPort authorizationPort;
    private final UnitOfWork unitOfWork;

    public CancelInventoryCount(
            InventoryCountRepository inventoryCountRepository,
            AuthorizationPort authorizationPort,
            UnitOfWork unitOfWork
    ) {
        this.inventoryCountRepository = inventoryCountRepository;
        this.authorizationPort = authorizationPort;
        this.unitOfWork = unitOfWork;
    }

    public Result<InventoryCountError, InventoryCount> execute(CancelInventoryCountCommand cmd, ActorId actorId) {
        if (!authorizationPort.can(actorId, InventoryAction.INVENTORY_COUNT_WRITE)) {
            return Result.failure(new InventoryCountError.Unauthorized("Not authorized to cancel inventory counts"));
        }

        if (cmd.inventoryCountId() == null || cmd.inventoryCountId().isBlank()) {
            return Result.failure(new InventoryCountError.InvalidInventoryCountId("must not be blank"));
        }

        InventoryCountId countId;
        try {
            countId = InventoryCountId.of(cmd.inventoryCountId());
        } catch (IllegalArgumentException e) {
            return Result.failure(new InventoryCountError.InvalidInventoryCountId(e.getMessage()));
        }

        InventoryCount inventoryCount;
        switch (inventoryCountRepository.findById(countId)) {
            case Result.Failure(var err) -> {
                return Result.failure(new InventoryCountError.RepositoryFailure(err.message()));
            }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new InventoryCountError.InventoryCountNotFound(cmd.inventoryCountId()));
                }
                inventoryCount = opt.get();
            }
        }

        switch (inventoryCount.cancel(cmd.reason())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        return unitOfWork.executeAtomically(() -> {
            switch (inventoryCountRepository.save(inventoryCount)) {
                case Result.Failure(var err) -> {
                    return Result.failure(new InventoryCountError.RepositoryFailure(err.message()));
                }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(inventoryCount);
        });
    }
}
