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 RecipeRepository recipeRepository;
    private final BatchNumberGenerator batchNumberGenerator;
    private final AuthorizationPort authorizationPort;
    private final UnitOfWork unitOfWork;

    public StartProductionOrder(
            ProductionOrderRepository productionOrderRepository,
            BatchRepository batchRepository,
            RecipeRepository recipeRepository,
            BatchNumberGenerator batchNumberGenerator,
            AuthorizationPort authorizationPort,
            UnitOfWork unitOfWork
    ) {
        this.productionOrderRepository = productionOrderRepository;
        this.batchRepository = batchRepository;
        this.recipeRepository = recipeRepository;
        this.batchNumberGenerator = batchNumberGenerator;
        this.authorizationPort = authorizationPort;
        this.unitOfWork = unitOfWork;
    }

    public Result<ProductionOrderError, StartProductionResult> 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 recipe
        Recipe recipe;
        switch (recipeRepository.findById(order.recipeId())) {
            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(
                            "Recipe '" + order.recipeId().value() + "' not found"));
                }
                recipe = opt.get();
            }
        }

        // Recipe must be ACTIVE
        if (recipe.status() != RecipeStatus.ACTIVE) {
            return Result.failure(new ProductionOrderError.ValidationFailure(
                    "Recipe '" + recipe.id().value() + "' is not ACTIVE (current: " + recipe.status() + ")"));
        }

        // Calculate bestBeforeDate (validates shelfLifeDays internally)
        java.time.LocalDate bestBeforeDate;
        switch (recipe.calculateBestBeforeDate(order.plannedDate())) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.ValidationFailure(
                        "Recipe '" + recipe.id().value() + "' has no valid shelf life configured: " + err.message()));
            }
            case Result.Success(var val) -> bestBeforeDate = val;
        }

        // Generate batch number
        BatchNumber batchNumber;
        switch (batchNumberGenerator.generateNext(order.plannedDate())) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
            }
            case Result.Success(var val) -> batchNumber = val;
        }

        // Build BatchDraft from order data
        var batchDraft = new BatchDraft(
                order.recipeId().value(),
                order.plannedQuantity().amount().toPlainString(),
                order.plannedQuantity().uom().name(),
                order.plannedDate(),
                bestBeforeDate
        );

        // Create batch in PLANNED status
        Batch batch;
        switch (Batch.plan(batchDraft, batchNumber)) {
            case Result.Failure(var err) -> {
                return Result.failure(new ProductionOrderError.BatchCreationFailed(err.code(), err.message()));
            }
            case Result.Success(var val) -> batch = val;
        }

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

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

        // Persist both atomically (batch first due to FK constraint on production_orders.batch_id)
        return unitOfWork.executeAtomically(() -> {
            switch (batchRepository.save(batch)) {
                case Result.Failure(var err) -> {
                    return Result.failure(new ProductionOrderError.RepositoryFailure(err.message()));
                }
                case Result.Success(var ignored) -> { }
            }

            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(new StartProductionResult(order, batch));
        });
    }
}
