package shop.alien.store.util;

import org.apache.commons.lang3.StringUtils;
import shop.alien.store.dto.CommonPushVendorSendResult;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 厂商 task_id 字符串格式化与解析，格式：oppo_task_id: 1001, honor_task_id: 10056
 */
public final class CommonPushVendorTaskIdUtil {

    private CommonPushVendorTaskIdUtil() {
    }

    /**
     * 将各厂商 task_id Map 格式化为入库字符串（common_push_task.vendor_task_ids）。
     * <p>格式转换：</p>
     * <pre>
     * 转换前 Map: { "huawei_task_id": "178169515953238426090801", "oppo_message_id": "msg123" }
     * 转换后 String: "huawei_task_id: 178169515953238426090801, oppo_message_id: msg123"
     * </pre>
     */
    public static String format(Map<String, String> vendorTaskIds) {
        if (vendorTaskIds == null || vendorTaskIds.isEmpty()) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : vendorTaskIds.entrySet()) {
            if (StringUtils.isAnyBlank(entry.getKey(), entry.getValue())) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(entry.getKey().trim()).append(": ").append(entry.getValue().trim());
        }
        return sb.length() == 0 ? null : sb.toString();
    }

    public static Map<String, String> parse(String vendorTaskIds) {
        Map<String, String> result = new LinkedHashMap<>();
        if (StringUtils.isBlank(vendorTaskIds)) {
            return result;
        }
        String[] parts = vendorTaskIds.split(",");
        for (String part : parts) {
            if (StringUtils.isBlank(part)) {
                continue;
            }
            int colonIndex = part.indexOf(':');
            if (colonIndex <= 0) {
                continue;
            }
            String key = part.substring(0, colonIndex).trim();
            String value = part.substring(colonIndex + 1).trim();
            if (StringUtils.isNoneBlank(key, value)) {
                result.put(key, value);
            }
        }
        return result;
    }

    /**
     * 广播/批量推送成功后写入厂商 task_id（key 规则：{channelCode}_task_id）。
     * <p>格式转换：</p>
     * <pre>
     * 转换前: channelCode="huawei", sendResult.vendorTaskId="178169515953238426090801"
     * 转换后 Map 条目: huawei_task_id -> 178169515953238426090801
     * </pre>
     */
    public static void putTaskId(Map<String, String> vendorTaskIds, String channelCode,
                                 CommonPushVendorSendResult sendResult) {
        if (vendorTaskIds == null || sendResult == null || !sendResult.isSuccess()) {
            return;
        }
        String code = StringUtils.lowerCase(StringUtils.trimToEmpty(channelCode));
        if (StringUtils.isNotBlank(sendResult.getVendorTaskId())) {
            vendorTaskIds.put(code + "_task_id", sendResult.getVendorTaskId().trim());
        }
        if (StringUtils.isNotBlank(sendResult.getExtraTaskId())) {
            vendorTaskIds.put(code + "_message_id", sendResult.getExtraTaskId().trim());
        }
    }

    /** 单推成功时合并厂商 task_id（同渠道多次推送用逗号拼接）。 */
    public static void mergeTaskId(Map<String, String> vendorTaskIds, String channelCode,
                                   CommonPushVendorSendResult sendResult) {
        if (vendorTaskIds == null || sendResult == null || !sendResult.isSuccess()) {
            return;
        }
        String code = StringUtils.lowerCase(StringUtils.trimToEmpty(channelCode));
        String taskKey = code + "_task_id";
        String messageKey = code + "_message_id";
        if (StringUtils.isNotBlank(sendResult.getVendorTaskId())) {
            String newId = sendResult.getVendorTaskId().trim();
            String existing = vendorTaskIds.get(taskKey);
            if (StringUtils.isBlank(existing)) {
                vendorTaskIds.put(taskKey, newId);
            } else if (!existing.contains(newId)) {
                vendorTaskIds.put(taskKey, existing + "," + newId);
            }
        }
        if (StringUtils.isNotBlank(sendResult.getExtraTaskId())) {
            vendorTaskIds.put(messageKey, sendResult.getExtraTaskId().trim());
        }
    }
}
