package com.lesingle.modules.pub.service;

import cn.hutool.core.util.RandomUtil;
import com.lesingle.modules.pub.config.SmsConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 短信发送服务
 * 封装阿里云短信 SDK，开发模式下验证码输出到日志
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsService {

    private final SmsConfig smsConfig;

    /**
     * 发送验证码短信
     *
     * @param phone 手机号
     * @param code  验证码
     */
    public void sendVerifyCode(String phone, String code) {
        if (!smsConfig.isEnabled()) {
            // 开发模式：验证码输出到日志
            log.info("【开发模式】短信验证码：手机号={}, 验证码={}", phone, code);
            return;
        }

        // 生产模式：调用阿里云短信 SDK
        try {
            com.aliyun.dysmsapi20170525.Client client = createClient();
            com.aliyun.dysmsapi20170525.models.SendSmsRequest request =
                    new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                            .setPhoneNumbers(phone)
                            .setSignName(smsConfig.getSignName())
                            .setTemplateCode(smsConfig.getTemplateCode())
                            .setTemplateParam("{\"code\":\"" + code + "\"}");

            com.aliyun.dysmsapi20170525.models.SendSmsResponse response = client.sendSms(request);

            if (response.getBody() == null || !"OK".equals(response.getBody().getCode())) {
                String errMsg = response.getBody() != null
                        ? response.getBody().getMessage() : "响应为空";
                log.error("短信发送失败：手机号={}, 错误码={}, 错误信息={}",
                        phone,
                        response.getBody() != null ? response.getBody().getCode() : "null",
                        errMsg);
                throw new RuntimeException("短信发送失败：" + errMsg);
            }

            log.info("短信发送成功：手机号={}", phone);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            log.error("短信发送异常：手机号={}", phone, e);
            throw new RuntimeException("短信发送异常", e);
        }
    }

    /**
     * 生成6位数字验证码
     */
    public String generateCode() {
        return RandomUtil.randomNumbers(6);
    }

    /**
     * 创建阿里云短信客户端
     */
    private com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                .setAccessKeyId(smsConfig.getAccessKeyId())
                .setAccessKeySecret(smsConfig.getAccessKeySecret());
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }
}
