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;
import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly = true)
public class FindBatchByNumber {

    private final BatchRepository batchRepository;
    private final AuthorizationPort authorizationPort;

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

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

        switch (batchRepository.findByBatchNumber(batchNumber)) {
            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.BatchNotFoundByNumber(batchNumber));
                }
                return Result.success(opt.get());
            }
        }
    }
}
