package de.effigenix.application.production;

import de.effigenix.application.production.command.CompleteProductionOrderCommand;
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 CompleteProductionOrder {

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

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

    public Result<ProductionOrderError, ProductionOrder> execute(CompleteProductionOrderCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)) {
            return Result.failure(new ProductionOrderError.Unauthorized("Not authorized to complete production orders"));
        }

        var orderId = ProductionOrderId.of(cmd.productionOrderId());
        ProductionOrder order;
        switch (productionOrderRepository.findById(orderId)) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
            }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new ProductionOrderError.ProductionOrderNotFound(orderId));
                }
                order = opt.get();
            }
        }

        // Batch must be COMPLETED (defense in depth – domain checks status transition)
        var batchId = order.batchId();
        if (batchId == null) {
            return Result.failure(new ProductionOrderError.ValidationFailure("Production order has no batch assigned"));
        }

        Batch batch;
        switch (batchRepository.findById(batchId)) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
            }
            case Result.Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new ProductionOrderError.ValidationFailure("Batch '" + batchId.value() + "' not found"));
                }
                batch = opt.get();
            }
        }

        if (batch.status() != BatchStatus.COMPLETED) {
            return Result.failure(new ProductionOrderError.BatchNotCompleted(batchId));
        }

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

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