package de.effigenix.application.production;

import de.effigenix.application.production.command.StartBatchCommand;
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
public class StartBatch {

    private final BatchRepository batchRepository;
    private final AuthorizationPort authorizationPort;

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

    public Result<BatchError, Batch> execute(StartBatchCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.BATCH_WRITE)) {
            return Result.failure(new BatchError.Unauthorized("Not authorized to start 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();
            }
        }

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

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