package com.agent.management.controller;

import com.agent.management.common.Result;
import com.agent.management.service.SseService;
import com.agent.management.service.TranslationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

/**
 * SSE 推送端点 + 同步翻译接口
 */
@Slf4j
@RestController
@RequestMapping("/api/translations")
@RequiredArgsConstructor
public class TranslationSseController {

    private final SseService sseService;
    private final TranslationService translationService;

    /**
     * SSE 翻译推送流
     * 前端通过 new EventSource('/api/translations/stream') 连接
     */
    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter stream() {
        return sseService.createEmitter();
    }

    /**
     * 同步翻译接口 — 编辑对话框中使用
     * 请求体: { "text": "English text" }
     * 返回: { "data": "翻译结果" }
     */
    @PostMapping("/translate")
    public Result<String> translate(@RequestBody Map<String, String> request) {
        String text = request.get("text");
        if (text == null || text.trim().isEmpty()) {
            return Result.success(text);
        }
        String translated = translationService.translateToChinese(text);
        return Result.success(translated);
    }
}
