package de.effigenix.application.production;

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

    private final BatchRepository batchRepository;
    private final RecipeRepository recipeRepository;
    private final BatchNumberGenerator batchNumberGenerator;
    private final AuthorizationPort authorizationPort;
    private final UnitOfWork unitOfWork;

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

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

        // Verify recipe exists and is ACTIVE
        Recipe recipe;
        switch (recipeRepository.findById(RecipeId.of(cmd.recipeId()))) {
            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.ValidationFailure(
                            "Recipe with ID '" + cmd.recipeId() + "' not found"));
                }
                recipe = opt.get();
            }
        }

        if (recipe.status() != RecipeStatus.ACTIVE) {
            return Result.failure(new BatchError.RecipeNotActive(recipe.id()));
        }

        // Generate batch number
        BatchNumber batchNumber;
        switch (batchNumberGenerator.generateNext(cmd.productionDate())) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> batchNumber = val;
        }

        // Plan batch
        var draft = new BatchDraft(
                cmd.recipeId(),
                cmd.plannedQuantity(),
                cmd.plannedQuantityUnit(),
                cmd.productionDate(),
                cmd.bestBeforeDate()
        );

        Batch batch;
        switch (Batch.plan(draft, batchNumber)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> batch = val;
        }

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