package de.effigenix.application.inventory;

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

    private final StorageLocationRepository storageLocationRepository;
    private final UnitOfWork unitOfWork;

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

    public Result<StorageLocationError, StorageLocation> execute(CreateStorageLocationCommand cmd, ActorId performedBy) {
        // 1. Draft aus Command bauen (kein VO-Wissen im Use Case)
        var draft = new StorageLocationDraft(
                cmd.name(), cmd.storageType(), cmd.minTemperature(), cmd.maxTemperature()
        );

        // 2. Aggregate erzeugen (validiert intern)
        StorageLocation location;
        switch (StorageLocation.create(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> location = val;
        }

        // 3. Uniqueness-Check (Application-Concern: braucht Repository)
        switch (storageLocationRepository.existsByName(location.name())) {
            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);
        });
    }
}
