package de.effigenix.application.production;

import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

public class GetBatch {

    private final BatchRepository batchRepository;
    private final AuthorizationPort authorizationPort;

    public GetBatch(BatchRepository batchRepository, AuthorizationPort authorizationPort) {
        this.batchRepository = batchRepository;
        this.authorizationPort = authorizationPort;
    }

    public Result<BatchError, Batch> execute(BatchId batchId, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.BATCH_READ)) {
            return Result.failure(new BatchError.Unauthorized("Not authorized to read batches"));
        }

        switch (batchRepository.findById(batchId)) {
            case Result.Failure(var err) ->
                { return Result.failure(new BatchError.RepositoryFailure(err.message())); }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new BatchError.BatchNotFound(batchId));
                }
                return Result.success(opt.get());
            }
        }
    }
}
