package org.dromara.talk.controller.api;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.talk.domain.dto.ConversationMessageRequest;
import org.dromara.talk.service.IWhatsAppHistoryService;
import org.springframework.web.bind.annotation.*;

/**
 * 对话历史记录API接口(对外)
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/talk/conversation")
@CrossOrigin(origins = "*", maxAge = 3600)
public class WhatsAppHistoryApiController {

    private final IWhatsAppHistoryService whatsAppHistoryService;

    /**
     * 接收对话消息（支持WhatsApp和ZoomPhone）
     */
    @PostMapping("/receive")
    public R<Void> receiveMessage(@RequestBody ConversationMessageRequest request) {
        try {
            log.info("接收到{}消息 - conversationId: {}, userId: {}, round: {}",
                request.getSource(), request.getConversationId(), request.getUserId(), request.getRound());

            // 根据source路由到不同的Service
            if ("whatsapp".equalsIgnoreCase(request.getSource())) {
                Boolean success = whatsAppHistoryService.receiveConversationMessage(request);
                if (Boolean.TRUE.equals(success)) {
                    return R.ok();
                } else {
                    return R.fail("保存WhatsApp消息失败");
                }
            } else if ("zoomphone".equalsIgnoreCase(request.getSource())) {
                // ZoomPhone消息不做处理，直接返回成功
                log.info("收到ZoomPhone消息，不做处理");
                return R.ok();
            }else{
                return R.fail("不支持的消息来源: " + request.getSource());
            }
        } catch (Exception e) {
            log.error("保存消息失败", e);
            return R.fail("保存消息失败: " + e.getMessage());
        }
    }


}
