package de.effigenix.application.inventory;

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

    private final StorageLocationRepository storageLocationRepository;
    private final UnitOfWork unitOfWork;

    public UpdateStorageLocation(StorageLocationRepository storageLocationRepository, UnitOfWork unitOfWork) {
        this.storageLocationRepository = storageLocationRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<StorageLocationError, StorageLocation> execute(UpdateStorageLocationCommand cmd, ActorId performedBy) {
        // 1. Laden
        var locationId = StorageLocationId.of(cmd.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(cmd.storageLocationId()));
                }
                location = opt.get();
            }
        }

        // 2. Draft bauen + Aggregate validieren lassen
        var draft = new StorageLocationUpdateDraft(cmd.name(), cmd.minTemperature(), cmd.maxTemperature());
        switch (location.update(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // 3. Uniqueness-Check (nur wenn Name geändert wurde)
        if (cmd.name() != null) {
            switch (storageLocationRepository.existsByNameAndIdNot(location.name(), locationId)) {
                case Result.Failure(var err) ->
                        { return Result.failure(new StorageLocationError.RepositoryFailure(err.message())); }
                case Result.Success(var exists) -> {
                    if (exists) {
                        return Result.failure(new StorageLocationError.NameAlreadyExists(cmd.name()));
                    }
                }
            }
        }

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