package de.effigenix.application.production;

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

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

    public StartProductionOrder(
            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(StartProductionOrderCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.PRODUCTION_ORDER_WRITE)) {
            return Result.failure(new ProductionOrderError.Unauthorized("Not authorized to start production orders"));
        }

        // Load production order
        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();
            }
        }

        // Load batch
        var batchId = BatchId.of(cmd.batchId());
        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 '" + cmd.batchId() + "' not found"));
                }
                batch = opt.get();
            }
        }

        // Batch must be PLANNED
        if (batch.status() != BatchStatus.PLANNED) {
            return Result.failure(new ProductionOrderError.ValidationFailure(
                    "Batch '" + cmd.batchId() + "' is not in PLANNED status (current: " + batch.status() + ")"));
        }

        // Batch must reference the same recipe as the order
        if (!batch.recipeId().equals(order.recipeId())) {
            return Result.failure(new ProductionOrderError.ValidationFailure(
                    "Batch recipe '" + batch.recipeId().value() + "' does not match order recipe '" + order.recipeId().value() + "'"));
        }

        // Start production on order (RELEASED -> IN_PROGRESS, assigns batchId)
        switch (order.startProduction(batchId)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var ignored) -> { }
        }

        // Start production on batch (PLANNED -> IN_PRODUCTION)
        switch (batch.startProduction()) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.ValidationFailure(err.message()));
            }
            case Result.Success(var ignored) -> { }
        }

        // Persist both atomically
        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) -> { }
            }

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

            return Result.success(order);
        });
    }
}
