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 ActivateStorageLocation {

    private final StorageLocationRepository storageLocationRepository;
    private final UnitOfWork unitOfWork;

    public ActivateStorageLocation(StorageLocationRepository storageLocationRepository, UnitOfWork unitOfWork) {
        this.storageLocationRepository = storageLocationRepository;
        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. Aktivieren
        switch (location.activate()) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. 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);
        });
    }
}
