package de.effigenix.application.masterdata;

import de.effigenix.application.masterdata.command.AddCertificateCommand;
import de.effigenix.domain.masterdata.*;
import de.effigenix.shared.common.Result;
import de.effigenix.shared.security.ActorId;
import org.springframework.transaction.annotation.Transactional;

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

@Transactional
public class AddCertificate {

    private final SupplierRepository supplierRepository;

    public AddCertificate(SupplierRepository supplierRepository) {
        this.supplierRepository = supplierRepository;
    }

    public Result<SupplierError, Supplier> execute(AddCertificateCommand 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();
            }
        }

        QualityCertificate certificate;
        switch (QualityCertificate.create(cmd.certificateType(), cmd.issuer(), cmd.validFrom(), cmd.validUntil())) {
            case Failure(var msg) -> { return Result.failure(new SupplierError.ValidationFailure(msg)); }
            case Success(var val) -> certificate = val;
        }
        supplier.addCertificate(certificate);

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

        return Result.success(supplier);
    }
}
