package com.usky.vpp.service.impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.usky.common.core.exception.BusinessException;
import com.usky.vpp.config.VppSmsProperties;
import com.usky.vpp.service.VppAliyunSmsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 阿里云短信服务实现
 */
@Service
public class VppAliyunSmsServiceImpl implements VppAliyunSmsService {

    private static final Logger log = LoggerFactory.getLogger(VppAliyunSmsServiceImpl.class);

    @Value("${sms.ali.region-id:}")
    private String regionId;

    @Value("${sms.ali.access-key-id:}")
    private String accessKeyId;

    @Value("${sms.ali.access-key-secret:}")
    private String accessKeySecret;

    @Autowired
    private VppSmsProperties smsProperties;

    @Override
    public void sendTemplateSms(String phone, String templateCode, String templateParam) {
        if (!Boolean.TRUE.equals(smsProperties.getEnabled())) {
            throw new BusinessException("短信服务未启用");
        }
        if (!StringUtils.hasText(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        if (!StringUtils.hasText(templateCode)) {
            throw new BusinessException("短信模板不能为空");
        }
        if (!StringUtils.hasText(smsProperties.getSignName())) {
            throw new BusinessException("短信签名未配置，请设置 vpp.sms.sign-name");
        }
        ensureCredentialsConfigured();

        try {
            DefaultProfile profile = DefaultProfile.getProfile(regionId.trim(), accessKeyId.trim(), accessKeySecret.trim());
            IAcsClient client = new DefaultAcsClient(profile);

            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(phone.trim());
            request.setSignName(smsProperties.getSignName().trim());
            request.setTemplateCode(templateCode.trim());
            if (StringUtils.hasText(templateParam)) {
                request.setTemplateParam(templateParam);
            }

            SendSmsResponse response = client.getAcsResponse(request);
            if (response == null || !"OK".equalsIgnoreCase(response.getCode())) {
                String message = response != null ? response.getMessage() : "无响应";
                log.warn("阿里云短信发送失败 phone={} template={} code={} message={}",
                        phone, templateCode, response != null ? response.getCode() : null, message);
                throw new BusinessException("短信发送失败: " + message);
            }
            log.info("阿里云短信发送成功 phone={} template={} bizId={}", phone, templateCode, response.getBizId());
        } catch (BusinessException ex) {
            throw ex;
        } catch (Exception ex) {
            log.warn("阿里云短信发送异常 phone={} template={}: {}", phone, templateCode, ex.getMessage());
            throw new BusinessException("短信发送失败: " + ex.getMessage());
        }
    }

    private void ensureCredentialsConfigured() {
        if (!StringUtils.hasText(regionId) || !StringUtils.hasText(accessKeyId) || !StringUtils.hasText(accessKeySecret)) {
            throw new BusinessException("阿里云短信密钥未配置，请在 Nacos 配置 sms.ali.region-id / access-key-id / access-key-secret");
        }
    }
}
