package de.effigenix.application.production;

import de.effigenix.application.production.command.CompleteBatchCommand;
import de.effigenix.domain.production.*;
import de.effigenix.domain.production.event.BatchCompleted;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.event.DomainEventPublisher;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;
import de.effigenix.shared.security.AuthorizationPort;

import java.time.Instant;

public class CompleteBatch {

    private final BatchRepository batchRepository;
    private final RecipeRepository recipeRepository;
    private final AuthorizationPort authorizationPort;
    private final DomainEventPublisher domainEventPublisher;
    private final UnitOfWork unitOfWork;

    public CompleteBatch(BatchRepository batchRepository, RecipeRepository recipeRepository,
                         AuthorizationPort authorizationPort, DomainEventPublisher domainEventPublisher,
                         UnitOfWork unitOfWork) {
        this.batchRepository = batchRepository;
        this.recipeRepository = recipeRepository;
        this.authorizationPort = authorizationPort;
        this.domainEventPublisher = domainEventPublisher;
        this.unitOfWork = unitOfWork;
    }

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

        var draft = new CompleteBatchDraft(
                cmd.actualQuantity(),
                cmd.actualQuantityUnit(),
                cmd.waste(),
                cmd.wasteUnit(),
                cmd.remarks()
        );

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

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

            // Load recipe to get articleId for the event
            Recipe recipe;
            switch (recipeRepository.findById(batch.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.RepositoryFailure(
                                "Recipe not found: " + batch.recipeId().value()));
                    }
                    recipe = opt.get();
                }
            }

            domainEventPublisher.publish(new BatchCompleted(
                    batch.id(),
                    batch.batchNumber(),
                    batch.recipeId(),
                    recipe.articleId(),
                    batch.actualQuantity(),
                    batch.waste(),
                    batch.bestBeforeDate(),
                    batch.completedAt(),
                    Instant.now()
            ));

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