package com.jeesharp.business.modules.pay.paychannelconfig.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.paychannelconfig.PayChannelPlatformDefaultConfigCode;
import com.jeesharp.business.modules.pay.paychannelconfig.entity.PayChannelConfig;
import com.jeesharp.business.modules.pay.paychannelconfig.enums.PayChannelCodeEnum;
import com.jeesharp.business.modules.pay.paychannelconfig.enums.PayChannelConfigStatusEnum;
import com.jeesharp.business.modules.pay.paychannelconfig.service.PayChannelConfigService;
import com.jeesharp.business.modules.pay.paywechatconfig.entity.PayWechatConfig;
import com.jeesharp.business.modules.pay.paywechatconfig.enums.PayWechatConfigStatusEnum;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 保存微信子配置时同步维护 {@code pay_channel_config} 主表记录。
 * <p>须走 {@link PayChannelConfigService#createPayChannelConfig} / {@link PayChannelConfigService#updatePayChannelConfig}，
 * 避免对平台租户主表误用通用 {@code save} 整单覆盖（平台仅允许回调字段变更）。</p>
 *
 * @author jeesharp
 * @since 2026-05-25
 */
@Component
@RequiredArgsConstructor
public class PayChannelWechatSyncSupport {

    private final PayChannelConfigService payChannelConfigService;

    /**
     * 根据微信配置 upsert 渠道主表，并回填 {@code channelConfigId}。
     */
    public void syncFromWechat(PayWechatConfig wechat) {
        if (wechat == null) {
            return;
        }
        String configCode = StrUtil.blankToDefault(wechat.getConfigCode(), "DEFAULT");
        PayChannelConfig channel = null;
        if (StrUtil.isNotBlank(wechat.getChannelConfigId())) {
            channel = payChannelConfigService.get(wechat.getChannelConfigId());
        }
        if (channel == null) {
            channel = payChannelConfigService.findByChannelAndConfigCode(
                    PayChannelCodeEnum.WECHAT.getCode(), configCode, wechat.getTenantId());
        }
        // 子表/前端仍传 DEFAULT，主表平台种子已用 DEFAULT_WECHAT，避免每次保存误判新建主表行
        if (channel == null && "DEFAULT".equalsIgnoreCase(StrUtil.trim(configCode))) {
            channel = payChannelConfigService.findByChannelAndConfigCode(
                    PayChannelCodeEnum.WECHAT.getCode(), PayChannelPlatformDefaultConfigCode.WECHAT, wechat.getTenantId());
        }
        boolean isNew = channel == null;
        if (isNew) {
            channel = new PayChannelConfig();
            channel.setChannelCode(PayChannelCodeEnum.WECHAT.getCode());
            channel.setConfigCode(configCode);
            channel.setDelFlag("0");
            channel.setSort(0);
        }
        channel.setConfigName(StrUtil.blankToDefault(wechat.getConfigName(), "微信支付"));
        Integer status = wechat.getStatus() != null ? wechat.getStatus() : PayChannelConfigStatusEnum.ENABLED.getValue();
        channel.setStatus(status);
        channel.setNotifyBaseUrl(wechat.getNotifyBaseUrl());
        channel.setPayCenterNotifyPath(StrUtil.blankToDefault(wechat.getPayCenterNotifyPath(),
                "/api/pay/payNotify/wxNotify"));
        // 前端专项页不传 tenantCode；勿用 null 覆盖已从库加载的主表租户字段，否则 update WHERE tenant_code 匹配失败
        if (StrUtil.isNotBlank(wechat.getTenantId())) {
            channel.setTenantId(wechat.getTenantId());
        }
        if (StrUtil.isNotBlank(wechat.getTenantCode())) {
            channel.setTenantCode(wechat.getTenantCode());
        }
        if (isNew) {
            payChannelConfigService.createPayChannelConfig(channel);
        } else {
            payChannelConfigService.updatePayChannelConfig(channel);
        }
        wechat.setChannelConfigId(channel.getId());
        if (PayWechatConfigStatusEnum.ENABLED.getValue().equals(wechat.getStatus())) {
            wechat.setStatus(PayChannelConfigStatusEnum.ENABLED.getValue());
        }
    }
}
