package de.effigenix.application.inventory;

import de.effigenix.application.inventory.command.CompleteInventoryCountCommand;
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;

import java.util.List;

public class CompleteInventoryCount {

    private final InventoryCountRepository inventoryCountRepository;
    private final StockRepository stockRepository;
    private final StockMovementRepository stockMovementRepository;
    private final InventoryCountReconciliationService reconciliationService;
    private final UnitOfWork unitOfWork;
    private final AuthorizationPort authPort;

    public CompleteInventoryCount(InventoryCountRepository inventoryCountRepository,
                                   StockRepository stockRepository,
                                   StockMovementRepository stockMovementRepository,
                                   InventoryCountReconciliationService reconciliationService,
                                   UnitOfWork unitOfWork,
                                   AuthorizationPort authPort) {
        this.inventoryCountRepository = inventoryCountRepository;
        this.stockRepository = stockRepository;
        this.stockMovementRepository = stockMovementRepository;
        this.reconciliationService = reconciliationService;
        this.unitOfWork = unitOfWork;
        this.authPort = authPort;
    }

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

        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()));
        }

        // 1. InventoryCount laden
        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();
            }
        }

        // 2. Inventur abschließen (Vier-Augen-Prinzip, Vollständigkeit)
        switch (count.complete(cmd.completedBy())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. Stocks für StorageLocation laden
        List<Stock> stocks;
        switch (stockRepository.findAllByStorageLocationId(count.storageLocationId())) {
            case Result.Failure(var err) ->
                    { return Result.failure(new InventoryCountError.RepositoryFailure(err.message())); }
            case Result.Success(var val) -> stocks = val;
        }

        // 4. Reconciliation: Ausgleichsbuchungen erzeugen
        List<StockMovementDraft> movementDrafts;
        switch (reconciliationService.reconcile(count, stocks, cmd.completedBy())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> movementDrafts = val;
        }

        // 5. StockMovements erzeugen und validieren
        List<StockMovement> movements = new java.util.ArrayList<>();
        for (StockMovementDraft draft : movementDrafts) {
            switch (StockMovement.record(draft)) {
                case Result.Failure(var err) ->
                        { return Result.failure(new InventoryCountError.RepositoryFailure(err.message())); }
                case Result.Success(var val) -> movements.add(val);
            }
        }

        // 6. Atomar speichern
        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) -> { }
            }

            for (StockMovement movement : movements) {
                switch (stockMovementRepository.save(movement)) {
                    case Result.Failure(var err) ->
                            { return Result.failure(new InventoryCountError.RepositoryFailure(err.message())); }
                    case Result.Success(var ignored) -> { }
                }
            }

            return Result.success(count);
        });
    }
}
