package cn.novalon.gym.manage.member.util;

import cn.novalon.gym.manage.member.service.WechatApiService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 微信手机号获取工具类
 * 
 * @author 付嘉
 * @date 2026-05-01
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class WechatPhoneUtil {

    private final WechatApiService wechatApiService;

    /**
     * 通过phoneCode获取手机号
     * 
     * @param phoneCode 手机号 code
     * @return Mono<String> 手机号，获取失败则返回 null
     */
    public Mono<String> getPhoneNumber(String phoneCode) {
        if (phoneCode == null || phoneCode.isEmpty()) {
            log.debug("未提供phoneCode获取手机号");
            return Mono.empty();
        }
        
        log.info("开始获取手机号, phoneCode: {}", phoneCode);
        
        return wechatApiService.getPhoneNumber(phoneCode)
                .doOnSuccess(phoneNumber -> {
                    if (phoneNumber != null && !phoneNumber.isEmpty()) {
                        log.info("获取手机号成功: {}", maskPhone(phoneNumber));
                    } else {
                        log.warn("获取手机号失败");
                    }
                })
                .doOnError(e -> {
                    log.warn("获取手机号失败 {}", e.getMessage());
                })
                .onErrorResume(e -> {
                    return Mono.empty();
                });
    }

    /**
     * 手机号脱敏处理
     * 
     * @param phone 手机号
     * @return 脱敏后的手机号，如：138****8000
     */
    public static String maskPhone(String phone) {
        if (phone == null || phone.length() < 7) {
            return "***";
        }
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }
}
