package com.dora.controller;

import com.dora.common.Result;
import com.dora.service.MsmService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 短信服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/user/msm")
@RequiredArgsConstructor
@Tag(name = "短信服务", description = "短信验证码相关接口")
public class MsmController {

    private final MsmService msmService;
    private final RedisTemplate<String, String> redisTemplate;

    @GetMapping("/send/{phone}")
    @Operation(summary = "发送短信验证码", description = "向指定手机号发送6位数字验证码。当force=true时，即使存在未过期的验证码也会强制发送新验证码")
    public Result<Boolean> sendSmsCode(
            @Parameter(description = "手机号", example = "13800138000") 
            @PathVariable String phone,
            @Parameter(description = "是否强制发送新验证码，默认false", example = "false")
            @RequestParam(defaultValue = "false") boolean force) {
        try {
            log.info("发送短信验证码 - phone: {}, force: {}", phone, force);

            // 1、从redis中获取验证码，如果获取到且不是强制发送就直接返回
            String existingCode = redisTemplate.opsForValue().get(phone);
            if (existingCode != null && !force) {
                log.warn("验证码已存在，请稍后再试 - phone: {}", phone);
                return Result.error(400, "验证码已存在，请稍后再试");
            }

            // 2、生成6位随机验证码
            String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
            
            // 如果是强制发送，记录覆盖信息
            if (existingCode != null && force) {
                log.info("强制发送新验证码，覆盖已存在的验证码 - phone: {}", phone);
            }

            // 3、调用短信服务发送验证码
            Map<String, Object> param = new HashMap<>();
            param.put("code", code);
            boolean isSend = msmService.send(param, phone);
            if(isSend) {
                // 4、发送成功，将验证码存储到redis，设置5分钟过期
                redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
                log.info("短信验证码发送成功 - phone: {}, code: {}, force: {}", phone, code, force);
                return Result.success(true);
            } else {
                log.error("短信验证码发送失败 - phone: {}, force: {}", phone, force);
                return Result.error(500, "短信发送失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("发送短信验证码异常 - phone: {}", phone, e);
            return Result.error(500, "发送短信验证码失败");
        }
    }
} 