package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.VerificationCodeService;

/**
 * 验证码控制器
 */
@RestController
@RequestMapping("/api/verification")
public class VerificationCodeController {
    
    private static final Logger logger = LoggerFactory.getLogger(VerificationCodeController.class);
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    
    /**
     * 发送邮件验证码
     */
    @PostMapping("/email/send")
    public ResponseEntity<Map<String, Object>> sendEmailCode(@RequestBody Map<String, String> request) {
        logger.info("收到发送验证码请求，参数: {}", request);
        Map<String, Object> response = new HashMap<>();
        
        String email = request.get("email");
        if (email == null || email.trim().isEmpty()) {
            logger.warn("验证码发送请求失败：邮箱为空");
            response.put("success", false);
            response.put("message", "邮箱不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 简单的邮箱格式验证
        if (!email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")) {
            logger.warn("验证码发送请求失败：邮箱格式不正确，邮箱: {}", email);
            response.put("success", false);
            response.put("message", "邮箱格式不正确");
            return ResponseEntity.badRequest().body(response);
        }
        
        logger.info("开始发送验证码到邮箱: {}", email);
        try {
            boolean success = verificationCodeService.sendEmailVerificationCode(email);
            if (success) {
                logger.info("验证码发送成功，邮箱: {}", email);
                response.put("success", true);
                response.put("message", "验证码发送成功");
            } else {
                logger.warn("验证码发送失败，邮箱: {}", email);
                response.put("success", false);
                response.put("message", "验证码发送失败，请稍后重试");
            }
        } catch (Exception e) {
            logger.error("验证码发送异常，邮箱: {}", email, e);
            response.put("success", false);
            response.put("message", "验证码发送失败：" + e.getMessage());
        }
        
        logger.info("验证码发送请求处理完成，邮箱: {}, 结果: {}", email, response.get("success"));
        return ResponseEntity.ok(response);
    }
    
    
    /**
     * 验证邮件验证码
     */
    @PostMapping("/email/verify")
    public ResponseEntity<Map<String, Object>> verifyEmailCode(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        String email = request.get("email");
        String code = request.get("code");
        
        if (email == null || email.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "邮箱不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        if (code == null || code.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "验证码不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            boolean success = verificationCodeService.verifyEmailCode(email, code);
            if (success) {
                response.put("success", true);
                response.put("message", "验证码验证成功");
            } else {
                response.put("success", false);
                response.put("message", "验证码错误或已过期");
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "验证码验证失败：" + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 开发模式：设置验证码（仅开发环境使用）
     */
    @PostMapping("/email/dev-set")
    public ResponseEntity<Map<String, Object>> setDevCode(@RequestBody Map<String, String> request) {
        Map<String, Object> response = new HashMap<>();
        
        // 仅开发环境允许
        if (!"dev".equals(System.getProperty("spring.profiles.active")) && 
            !"development".equals(System.getProperty("spring.profiles.active"))) {
            response.put("success", false);
            response.put("message", "此接口仅开发环境可用");
            return ResponseEntity.badRequest().body(response);
        }
        
        String email = request.get("email");
        String code = request.get("code");
        
        if (email == null || email.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "邮箱不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        if (code == null || code.trim().isEmpty()) {
            response.put("success", false);
            response.put("message", "验证码不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            // 直接设置验证码到内存存储
            verificationCodeService.setVerificationCode(email, code);
            
            response.put("success", true);
            response.put("message", "开发模式验证码设置成功");
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "设置验证码失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
