package de.effigenix.application.inventory;

import de.effigenix.domain.inventory.*;
import de.effigenix.shared.common.RepositoryError;
import de.effigenix.shared.common.Result;

import java.util.List;

public class ListStorageLocations {

    private final StorageLocationRepository storageLocationRepository;

    public ListStorageLocations(StorageLocationRepository storageLocationRepository) {
        this.storageLocationRepository = storageLocationRepository;
    }

    public Result<StorageLocationError, List<StorageLocation>> execute(String storageType, Boolean active) {
        if (storageType != null) {
            return findByStorageType(storageType, active);
        }
        return mapResult(storageLocationRepository.findAll())
                .map(locations -> filterByActive(locations, active));
    }

    private Result<StorageLocationError, List<StorageLocation>> findByStorageType(String storageType, Boolean active) {
        StorageType type;
        try {
            type = StorageType.valueOf(storageType);
        } catch (IllegalArgumentException e) {
            return Result.failure(new StorageLocationError.InvalidStorageType(storageType));
        }

        return mapResult(storageLocationRepository.findByStorageType(type))
                .map(locations -> filterByActive(locations, active));
    }

    private List<StorageLocation> filterByActive(List<StorageLocation> locations, Boolean active) {
        if (active == null) {
            return locations;
        }
        return locations.stream()
                .filter(loc -> loc.active() == active)
                .toList();
    }

    private Result<StorageLocationError, List<StorageLocation>> mapResult(
            Result<RepositoryError, List<StorageLocation>> result) {
        return switch (result) {
            case Result.Failure(var err) -> Result.failure(new StorageLocationError.RepositoryFailure(err.message()));
            case Result.Success(var locations) -> Result.success(locations);
        };
    }
}
