package ru.yandex.webmaster3.storage.turbo.service.preview.commerce;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.Builder;
import lombok.Value;

import ru.yandex.webmaster3.core.turbo.model.TurboHostSettings;
import ru.yandex.webmaster3.core.turbo.model.commerce.TurboCommerceSettings;
import ru.yandex.webmaster3.core.util.json.JsonMapping;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Oleg Bazdyrev on 19/11/2018.
 */
@Value
@Builder
public class OrderInfo {

    @JsonProperty("handlers")
    private final List<ObjectNode> handlers;
    @JsonProperty("agreement_company")
    private final String agreementCompany;
    @JsonProperty("agreement_link")
    private final String agreementLink;
    @JsonProperty("min_cost")
    private final BigDecimal minOrderValue;

    public static OrderInfo fromSettings(TurboHostSettings settings) {
        TurboCommerceSettings commerceSettings = settings.getCommerceSettings();
        if (commerceSettings == null) {
            return null;
        }
        List<ObjectNode> handlers = new ArrayList<>();
        if (commerceSettings.isTurboCartEnabled() || commerceSettings.isCheckoutEmailEnabled()) {
            handlers.add(JsonMapping.OM.createObjectNode()
                    .put("type", "email")
                    .put("value", commerceSettings.getCheckoutEmail())
            );

            if (commerceSettings.getBitrixSettings() != null && commerceSettings.getBitrixSettings().isEnabled()) {
                handlers.add(JsonMapping.OM.createObjectNode()
                        .put("type", "bitrix")
                        .put("token", commerceSettings.getBitrixSettings().getEncryptedToken())
                        .put("api_base_url", commerceSettings.getBitrixSettings().getApiBaseUrl())
                );
            }
        }
        String agreementCompany = null;
        String agreementLink = null;
        if (settings.getUserAgreement() != null) {
            agreementCompany = settings.getUserAgreement().getAgreementCompany();
            agreementLink = settings.getUserAgreement().getAgreementLink();
        }
        return new OrderInfo(handlers, agreementCompany, agreementLink, commerceSettings.getMinOrderValue());
    }

}
