package com.example.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

/**
 * 腾讯云SES Webhook控制器
 * 用于接收SES服务的推送数据
 */
@RestController
@RequestMapping("/api/email")
public class SesWebhookController {

    private static final Logger logger = LoggerFactory.getLogger(SesWebhookController.class);

    /**
     * 处理邮件发送状态回调
     * 当邮件发送成功或失败时，SES会推送状态信息
     */
    @PostMapping("/send-status")
    public ResponseEntity<Map<String, Object>> handleSendStatus(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件发送状态回调: {}", data);
        
        try {
            // 解析SES推送的数据
            String messageId = (String) data.get("MessageId");
            String status = (String) data.get("Status");
            String email = (String) data.get("Email");
            String timestamp = (String) data.get("Timestamp");
            
            logger.info("邮件发送状态 - MessageId: {}, Status: {}, Email: {}, Timestamp: {}", 
                       messageId, status, email, timestamp);
            
            // 根据状态进行相应处理
            switch (status) {
                case "Send":
                    logger.info("邮件发送成功: {}", email);
                    // 可以更新数据库中的发送状态
                    break;
                case "Reject":
                    logger.warn("邮件发送被拒绝: {}", email);
                    // 处理发送被拒绝的情况
                    break;
                case "Bounce":
                    logger.warn("邮件发送失败(退信): {}", email);
                    // 处理退信情况
                    break;
                default:
                    logger.info("邮件发送状态: {} - {}", status, email);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "状态回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件发送状态回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理邮件投递状态回调
     * 当邮件被投递到收件人邮箱时，SES会推送投递状态
     */
    @PostMapping("/delivery-status")
    public ResponseEntity<Map<String, Object>> handleDeliveryStatus(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件投递状态回调: {}", data);
        
        try {
            String messageId = (String) data.get("MessageId");
            String status = (String) data.get("Status");
            String email = (String) data.get("Email");
            String timestamp = (String) data.get("Timestamp");
            
            logger.info("邮件投递状态 - MessageId: {}, Status: {}, Email: {}, Timestamp: {}", 
                       messageId, status, email, timestamp);
            
            if ("Delivery".equals(status)) {
                logger.info("邮件投递成功: {}", email);
                // 可以更新数据库中的投递状态
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "投递状态回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件投递状态回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理邮件退信回调
     * 当邮件无法投递时，SES会推送退信信息
     */
    @PostMapping("/bounce")
    public ResponseEntity<Map<String, Object>> handleBounce(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件退信回调: {}", data);
        
        try {
            String messageId = (String) data.get("MessageId");
            String email = (String) data.get("Email");
            String bounceType = (String) data.get("BounceType");
            String bounceSubType = (String) data.get("BounceSubType");
            String timestamp = (String) data.get("Timestamp");
            
            logger.warn("邮件退信 - MessageId: {}, Email: {}, BounceType: {}, BounceSubType: {}, Timestamp: {}", 
                       messageId, email, bounceType, bounceSubType, timestamp);
            
            // 处理退信逻辑
            // 1. 记录退信信息到数据库
            // 2. 如果是硬退信，可以考虑从邮件列表中移除该邮箱
            // 3. 如果是软退信，可以稍后重试
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "退信回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件退信回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理邮件投诉回调
     * 当收件人投诉邮件为垃圾邮件时，SES会推送投诉信息
     */
    @PostMapping("/complaint")
    public ResponseEntity<Map<String, Object>> handleComplaint(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件投诉回调: {}", data);
        
        try {
            String messageId = (String) data.get("MessageId");
            String email = (String) data.get("Email");
            String complaintType = (String) data.get("ComplaintType");
            String timestamp = (String) data.get("Timestamp");
            
            logger.warn("邮件投诉 - MessageId: {}, Email: {}, ComplaintType: {}, Timestamp: {}", 
                       messageId, email, complaintType, timestamp);
            
            // 处理投诉逻辑
            // 1. 记录投诉信息到数据库
            // 2. 考虑从邮件列表中移除该邮箱
            // 3. 检查邮件内容是否合规
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "投诉回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件投诉回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理邮件打开事件回调
     * 当收件人打开邮件时，SES会推送打开事件
     */
    @PostMapping("/open")
    public ResponseEntity<Map<String, Object>> handleOpen(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件打开事件回调: {}", data);
        
        try {
            String messageId = (String) data.get("MessageId");
            String email = (String) data.get("Email");
            String timestamp = (String) data.get("Timestamp");
            String userAgent = (String) data.get("UserAgent");
            String ipAddress = (String) data.get("IpAddress");
            
            logger.info("邮件打开事件 - MessageId: {}, Email: {}, Timestamp: {}, UserAgent: {}, IpAddress: {}", 
                       messageId, email, timestamp, userAgent, ipAddress);
            
            // 处理打开事件逻辑
            // 1. 记录邮件打开统计
            // 2. 更新用户活跃度
            // 3. 分析用户行为
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "打开事件回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件打开事件回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理邮件点击事件回调
     * 当收件人点击邮件中的链接时，SES会推送点击事件
     */
    @PostMapping("/click")
    public ResponseEntity<Map<String, Object>> handleClick(@RequestBody Map<String, Object> data) {
        logger.info("收到邮件点击事件回调: {}", data);
        
        try {
            String messageId = (String) data.get("MessageId");
            String email = (String) data.get("Email");
            String timestamp = (String) data.get("Timestamp");
            String link = (String) data.get("Link");
            String userAgent = (String) data.get("UserAgent");
            String ipAddress = (String) data.get("IpAddress");
            
            logger.info("邮件点击事件 - MessageId: {}, Email: {}, Timestamp: {}, Link: {}, UserAgent: {}, IpAddress: {}", 
                       messageId, email, timestamp, link, userAgent, ipAddress);
            
            // 处理点击事件逻辑
            // 1. 记录链接点击统计
            // 2. 分析用户兴趣
            // 3. 更新用户行为数据
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "点击事件回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理邮件点击事件回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 处理SES配置集事件回调
     * 当配置集状态发生变化时，SES会推送配置集事件
     */
    @PostMapping("/configuration-set")
    public ResponseEntity<Map<String, Object>> handleConfigurationSet(@RequestBody Map<String, Object> data) {
        logger.info("收到SES配置集事件回调: {}", data);
        
        try {
            String eventType = (String) data.get("EventType");
            String configurationSet = (String) data.get("ConfigurationSet");
            String timestamp = (String) data.get("Timestamp");
            
            logger.info("SES配置集事件 - EventType: {}, ConfigurationSet: {}, Timestamp: {}", 
                       eventType, configurationSet, timestamp);
            
            // 处理配置集事件逻辑
            // 1. 更新配置集状态
            // 2. 记录配置变更历史
            // 3. 发送通知给管理员
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "配置集事件回调处理成功");
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("处理SES配置集事件回调失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "处理失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}
