package de.effigenix.application.production;

import de.effigenix.application.production.command.CancelBatchCommand;
import de.effigenix.domain.production.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

public class CancelBatch {

    private final BatchRepository batchRepository;
    private final AuthorizationPort authorizationPort;
    private final UnitOfWork unitOfWork;

    public CancelBatch(BatchRepository batchRepository, AuthorizationPort authorizationPort, UnitOfWork unitOfWork) {
        this.batchRepository = batchRepository;
        this.authorizationPort = authorizationPort;
        this.unitOfWork = unitOfWork;
    }

    public Result<BatchError, Batch> execute(CancelBatchCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.BATCH_CANCEL)) {
            return Result.failure(new BatchError.Unauthorized("Not authorized to cancel batches"));
        }

        var batchId = BatchId.of(cmd.batchId());

        Batch batch;
        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));
                }
                batch = opt.get();
            }
        }

        var draft = new CancelBatchDraft(cmd.reason());

        switch (batch.cancel(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        return unitOfWork.executeAtomically(() -> {
            switch (batchRepository.save(batch)) {
                case Result.Failure(var err) -> {
                    return Result.failure(new BatchError.RepositoryFailure(err.message()));
                }
                case Result.Success(var ignored) -> { }
            }
            return Result.success(batch);
        });
    }
}
