package de.effigenix.application.production;

import de.effigenix.application.production.command.RecordConsumptionCommand;
import de.effigenix.domain.production.*;
import de.effigenix.domain.production.event.ConsumptionRecorded;
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 RecordConsumption {

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

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

    public Result<BatchError, Consumption> execute(RecordConsumptionCommand cmd, ActorId performedBy) {
        if (!authorizationPort.can(performedBy, ProductionAction.BATCH_WRITE)) {
            return Result.failure(new BatchError.Unauthorized("Not authorized to record consumptions"));
        }

        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 ConsumptionDraft(
                cmd.inputBatchId(),
                cmd.articleId(),
                cmd.quantityUsed(),
                cmd.quantityUnit()
        );

        Consumption consumption;
        switch (batch.recordConsumption(draft)) {
            case Result.Failure(var err) -> { return Result.failure(err); }
            case Result.Success(var val) -> consumption = 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) -> { }
            }

            domainEventPublisher.publish(new ConsumptionRecorded(
                    batchId,
                    consumption.id(),
                    consumption.inputBatchId().value(),
                    consumption.articleId().value(),
                    consumption.quantityUsed(),
                    Instant.now()
            ));

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