package de.effigenix.application.inventory;

import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

public class DeactivateStorageLocation {

    private final StorageLocationRepository storageLocationRepository;
    private final StockRepository stockRepository;
    private final UnitOfWork unitOfWork;

    public DeactivateStorageLocation(StorageLocationRepository storageLocationRepository, StockRepository stockRepository, UnitOfWork unitOfWork) {
        this.storageLocationRepository = storageLocationRepository;
        this.stockRepository = stockRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<StorageLocationError, StorageLocation> execute(String storageLocationId, ActorId performedBy) {
        // 1. Laden
        var locationId = StorageLocationId.of(storageLocationId);
        StorageLocation location;
        switch (storageLocationRepository.findById(locationId)) {
            case Result.Failure(var err) ->
                    { return Result.failure(new StorageLocationError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new StorageLocationError.StorageLocationNotFound(storageLocationId));
                }
                location = opt.get();
            }
        }

        // 2. Stock-Existenz prüfen
        switch (stockRepository.findAllByStorageLocationId(locationId)) {
            case Result.Failure(var err) ->
                    { return Result.failure(new StorageLocationError.RepositoryFailure(err.message())); }
            case Result.Success(var stocks) -> {
                if (!stocks.isEmpty()) {
                    return Result.failure(new StorageLocationError.StockExistsAtLocation(storageLocationId));
                }
            }
        }

        // 3. Deaktivieren
        switch (location.deactivate()) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 4. Speichern
        return unitOfWork.executeAtomically(() -> {
            switch (storageLocationRepository.save(location)) {
                case Result.Failure(var err) ->
                        { return Result.failure(new StorageLocationError.RepositoryFailure(err.message())); }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(location);
        });
    }
}
