package org.lingniu.idp.service.core;

import lombok.extern.slf4j.Slf4j;
import org.lingniu.idp.common.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SmsCodeService {
    
    @Autowired
    private RedisCache redisCache;
    
    private static final String SMS_CODE_PREFIX = "sms:code:";
    private static final long SMS_CODE_EXPIRE = 300; // 5分钟
    
    /**
     * 生成并发送验证码
     */
    public void sendSmsCode(String phone) {
        // 1. 生成验证码
        String code = generateCode();
        String key = SMS_CODE_PREFIX + phone;
        // 2. 存储到Redis
        redisCache.setCacheObject(
            key,
            code
        );
        redisCache.expire(key,SMS_CODE_EXPIRE);
        
        // 3. 发送短信（这里使用腾讯云示例，可根据实际情况替换）
        sendSms(phone, code);
        
        log.info("向手机号 {} 发送验证码: {}", phone, code);
    }
    
    /**
     * 验证短信验证码
     */
    public boolean verifyCode(String phone, String code) {
        String key = SMS_CODE_PREFIX + phone;
        String storedCode = (String) redisCache.getCacheObject(key);
        
        if (storedCode != null && storedCode.equals(code)) {
            // 验证成功后删除验证码
            redisCache.deleteObject(key);
            return true;
        }
        return false;
    }
    
    private String generateCode() {
        // 生成6位随机数字
        Random random = new Random();
        return String.format("%06d", random.nextInt(999999));
    }
    
    private void sendSms(String phone, String code) {
        try {
            // 腾讯云短信发送示例
//            Credential cred = new Credential("secretId", "secretKey");
//            SmsClient client = new SmsClient(cred, "ap-guangzhou");
//
//            SendSmsRequest req = new SendSmsRequest();
//            req.setPhoneNumberSet(new String[]{"+86" + phone});
//            req.setSmsSdkAppId("your_app_id");
//            req.setSignName("your_sign_name");
//            req.setTemplateId("your_template_id");
//            req.setTemplateParamSet(new String[]{code, "5"});
//
//            SendSmsResponse resp = client.SendSms(req);
//            log.info("短信发送响应: {}", SendSmsResponse.toJsonString(resp));
        } catch (Exception e) {
            log.error("短信发送失败", e);
        }
    }
}