package de.effigenix.application.inventory;

import de.effigenix.domain.inventory.InventoryAction;
import de.effigenix.domain.inventory.InventoryCount;
import de.effigenix.domain.inventory.InventoryCountError;
import de.effigenix.domain.inventory.InventoryCountId;
import de.effigenix.domain.inventory.InventoryCountRepository;
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 StartInventoryCount {

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

    public StartInventoryCount(InventoryCountRepository inventoryCountRepository,
                                UnitOfWork unitOfWork,
                                AuthorizationPort authPort) {
        this.inventoryCountRepository = inventoryCountRepository;
        this.unitOfWork = unitOfWork;
        this.authPort = authPort;
    }

    public Result<InventoryCountError, InventoryCount> execute(String inventoryCountId, ActorId actorId) {
        if (!authPort.can(actorId, InventoryAction.INVENTORY_COUNT_WRITE)) {
            return Result.failure(new InventoryCountError.Unauthorized("Not authorized to start inventory count"));
        }

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

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

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

        switch (count.startCounting()) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

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