package com.jeesharp.business.modules.marketing.application.support;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.marketing.tenantQrcode.dto.MarketingTenantQrcodeCreateDTO;
import com.jeesharp.business.modules.marketing.tenantQrcode.enums.MarketingChannelPresetEnum;
import com.jeesharp.framework.exception.BizErrorException;
import lombok.Getter;

import java.util.regex.Pattern;

/**
 * 推广码渠道预设解析与自定义渠道编码生成。
 *
 * @author jeesharp
 * @since 2026-06-26
 */
public final class MarketingChannelPresetSupport {

    private static final String CUSTOM_PRESET = "CUSTOM";
    private static final Pattern CHANNEL_CODE_PATTERN = Pattern.compile("^[A-Z0-9_]{2,32}$");

    private MarketingChannelPresetSupport() {
    }

    /**
     * 根据创建请求解析最终渠道编码与名称。
     */
    public static ResolvedChannel resolve(MarketingTenantQrcodeCreateDTO dto) {
        String presetCode = StrUtil.trim(dto.getPresetCode());
        if (StrUtil.isNotBlank(presetCode) && !CUSTOM_PRESET.equalsIgnoreCase(presetCode)) {
            MarketingChannelPresetEnum preset = MarketingChannelPresetEnum.fromCode(presetCode);
            if (preset == null) {
                throw new BizErrorException("无效的推广渠道，请重新选择");
            }
            return new ResolvedChannel(preset.getCode(), preset.getName());
        }
        if (StrUtil.isNotBlank(dto.getChannelCode())) {
            String code = normalizeChannelCode(dto.getChannelCode());
            String name = StrUtil.blankToDefault(StrUtil.trim(dto.getChannelName()),
                    MarketingChannelPresetEnum.nameForCode(code));
            return new ResolvedChannel(code, name);
        }
        String customName = StrUtil.trim(dto.getChannelName());
        if (StrUtil.isBlank(customName)) {
            throw new BizErrorException("请选择常用推广渠道，或填写自定义渠道名称");
        }
        if (customName.length() > 64) {
            throw new BizErrorException("自定义渠道名称不能超过64个字符");
        }
        return new ResolvedChannel(generateCustomChannelCode(), customName);
    }

    public static String generateCustomChannelCode() {
        String suffix = IdUtil.getSnowflakeNextIdStr();
        if (suffix.length() > 10) {
            suffix = suffix.substring(suffix.length() - 10);
        }
        return "CH" + suffix;
    }

    public static String normalizeChannelCode(String channelCode) {
        String code = StrUtil.trim(channelCode).toUpperCase();
        if (!CHANNEL_CODE_PATTERN.matcher(code).matches()) {
            throw new BizErrorException("渠道编码仅支持大写字母、数字与下划线，长度2～32");
        }
        return code;
    }

    @Getter
    public static final class ResolvedChannel {
        private final String channelCode;
        private final String channelName;

        public ResolvedChannel(String channelCode, String channelName) {
            this.channelCode = channelCode;
            this.channelName = channelName;
        }
    }
}
