package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.RecordCountItemCommand;
import de.effigenix.domain.inventory.CountItemId;
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.Quantity;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.common.UnitOfMeasure;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

import java.math.BigDecimal;

public class RecordCountItem {

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

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

    public Result<InventoryCountError, InventoryCount> execute(RecordCountItemCommand cmd, ActorId actorId) {
        if (!authPort.can(actorId, InventoryAction.INVENTORY_COUNT_WRITE)) {
            return Result.failure(new InventoryCountError.Unauthorized("Not authorized to record count items"));
        }

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

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

        CountItemId itemId;
        try {
            itemId = CountItemId.of(cmd.countItemId());
        } catch (IllegalArgumentException e) {
            return Result.failure(new InventoryCountError.InvalidCountItemId(e.getMessage()));
        }

        // Parse quantity
        BigDecimal amount;
        try {
            amount = new BigDecimal(cmd.actualQuantityAmount());
        } catch (NumberFormatException | NullPointerException e) {
            return Result.failure(new InventoryCountError.InvalidQuantity(
                    "Invalid quantity amount: " + cmd.actualQuantityAmount()));
        }

        UnitOfMeasure uom;
        try {
            uom = UnitOfMeasure.valueOf(cmd.actualQuantityUnit());
        } catch (IllegalArgumentException | NullPointerException e) {
            return Result.failure(new InventoryCountError.InvalidQuantity(
                    "Invalid unit: " + cmd.actualQuantityUnit()));
        }

        Quantity actualQuantity = Quantity.reconstitute(amount, uom);

        // Load aggregate
        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(cmd.inventoryCountId()));
                }
                count = optCount.get();
            }
        }

        switch (count.updateCountItem(itemId, actualQuantity)) {
            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);
        });
    }
}
