package com.zioinfo.cms.i18n;

import com.zioinfo.cms.ai.AiService;
import com.zioinfo.cms.common.ApiResponse;
import com.zioinfo.cms.i18n.mapper.I18nMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** 다국어/로케일 API — 번역 리소스 CRUD + AI 번역. */
@RestController
@RequestMapping("/api/cms/i18n")
@RequiredArgsConstructor
public class I18nController {

    private final I18nMapper mapper;
    private final AiService aiService;

    @GetMapping("/locales")
    public ApiResponse<List<String>> locales() {
        return ApiResponse.ok(mapper.findLocales());
    }

    @GetMapping("/resources")
    public ApiResponse<List<CmsI18n>> resources(@RequestParam(defaultValue = "ko") String locale) {
        return ApiResponse.ok(mapper.findByLocale(locale));
    }

    @PostMapping("/resources")
    public ApiResponse<Void> upsert(@RequestBody Map<String, String> req) {
        mapper.upsert(req.getOrDefault("locale", "ko"), req.get("resourceKey"), req.get("value"));
        return ApiResponse.ok(null);
    }

    @DeleteMapping("/resources/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        mapper.delete(id);
        return ApiResponse.ok(null);
    }

    /** AI 번역 — 텍스트를 대상 로케일로. */
    @PostMapping("/translate")
    public ApiResponse<Map<String, String>> translate(@RequestBody Map<String, String> req) {
        String out = aiService.translate(req.get("text"), req.getOrDefault("targetLocale", "en"));
        return ApiResponse.ok(Map.of("translated", out));
    }

    /** ko 리소스를 대상 로케일로 일괄 AI 번역 후 저장. */
    @PostMapping("/translate-batch")
    public ApiResponse<Map<String, Object>> translateBatch(@RequestBody Map<String, String> req) {
        String target = req.getOrDefault("targetLocale", "en");
        List<CmsI18n> source = mapper.findByLocale(req.getOrDefault("sourceLocale", "ko"));
        int count = 0;
        for (CmsI18n s : source) {
            String translated = aiService.translate(s.getValue(), target);
            mapper.upsert(target, s.getResourceKey(), translated);
            count++;
        }
        return ApiResponse.ok(Map.of("translated", count, "targetLocale", target));
    }
}
