package de.effigenix.application.masterdata.supplier;

import de.effigenix.application.masterdata.supplier.command.RemoveCertificateCommand;
import de.effigenix.domain.masterdata.supplier.Supplier;
import de.effigenix.domain.masterdata.supplier.SupplierError;
import de.effigenix.domain.masterdata.supplier.SupplierId;
import de.effigenix.domain.masterdata.supplier.SupplierRepository;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.persistence.UnitOfWork;
import de.effigenix.shared.security.ActorId;

import java.util.Objects;

import static de.effigenix.shared.common.Result.*;

public class RemoveCertificate {

    private final SupplierRepository supplierRepository;
    private final UnitOfWork unitOfWork;

    public RemoveCertificate(SupplierRepository supplierRepository, UnitOfWork unitOfWork) {
        this.supplierRepository = supplierRepository;
        this.unitOfWork = unitOfWork;
    }

    public Result<SupplierError, Supplier> execute(RemoveCertificateCommand cmd, ActorId performedBy) {
        var supplierId = SupplierId.of(cmd.supplierId());

        Supplier supplier;
        switch (supplierRepository.findById(supplierId)) {
            case Failure(var err) ->
                { return Result.failure(new SupplierError.RepositoryFailure(err.message())); }
            case Success(var opt) -> {
                if (opt.isEmpty()) {
                    return Result.failure(new SupplierError.SupplierNotFound(supplierId));
                }
                supplier = opt.get();
            }
        }

        var certificate = supplier.certificates().stream()
                .filter(c -> c.certificateType().equals(cmd.certificateType())
                        && Objects.equals(c.issuer(), cmd.issuer())
                        && Objects.equals(c.validFrom(), cmd.validFrom()))
                .findFirst();

        if (certificate.isEmpty()) {
            return Result.failure(new SupplierError.CertificateNotFound(cmd.certificateType()));
        }
        supplier.removeCertificate(certificate.get());

        return unitOfWork.executeAtomically(() -> {
            switch (supplierRepository.save(supplier)) {
                case Failure(var err) ->
                    { return Result.failure(new SupplierError.RepositoryFailure(err.message())); }
                case Success(var ignored) -> { }
            }
            return Result.success(supplier);
        });
    }
}
