package com.eactive.eai.manage.tools;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
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;

/**
 * base64 / hex / DAMO 변환을 브라우저나 Postman 등에서 바로 테스트할 수 있는 유틸리티 API.
 *
 * POST /manage/tools/base64/encode → 문자열 → Base64
 * POST /manage/tools/base64/decode → Base64 → 문자열
 * POST /manage/tools/hex/encode    → 문자열 → Hex
 * POST /manage/tools/hex/decode    → Hex → 문자열
 * POST /manage/tools/damo/encrypt  → 평문 → DAMO 암호문 (DamoManager 직접 호출)
 * POST /manage/tools/damo/decrypt  → DAMO 암호문 → 평문 (DamoManager 직접 호출)
 *
 * POST /manage/tools/encryption-manager/encrypt → EncryptionManager.encryptDBData 확인용
 * POST /manage/tools/encryption-manager/decrypt → EncryptionManager.decryptDBData 확인용
 * GET  /manage/tools/encryption-manager/status  → encryptYN/dbEncryptSolutionName 등 현재 설정 확인
 *
 * GET  /manage/tools/version → 배포된 게이트웨이(eapim-online.war)의 git 버전/빌드시각 확인.
 *                              eapim-online(WAR를 만드는 루트 프로젝트) build.gradle의
 *                              generateVersionInfo 태스크가 생성하는 classpath 리소스
 *                              version.info(git describe 결과) 기반. 재빌드 없이 기동한 로컬
 *                              환경 등 파일이 없으면 success=false로 응답한다
 *
 * base64/hex 변환은 요청 body의 charset(생략 시 UTF-8)을 기준으로 문자열 ↔ 바이트를 변환한다.
 */
@RestController
@RequestMapping("/manage/tools")
public class ToolsController {

    private static final MediaType APPLICATION_JSON_UTF8 = new MediaType("application", "json", StandardCharsets.UTF_8);

    @Autowired
    private ToolsService toolsService;

    @PostMapping("/base64/encode")
    public ResponseEntity<?> base64Encode(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.base64Encode(request.getText(), request.getCharset()));
    }

    @PostMapping("/base64/decode")
    public ResponseEntity<?> base64Decode(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.base64Decode(request.getText(), request.getCharset()));
    }

    @PostMapping("/hex/encode")
    public ResponseEntity<?> hexEncode(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.hexEncode(request.getText(), request.getCharset()));
    }

    @PostMapping("/hex/decode")
    public ResponseEntity<?> hexDecode(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.hexDecode(request.getText(), request.getCharset()));
    }

    @PostMapping("/damo/encrypt")
    public ResponseEntity<?> damoEncrypt(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.damoEncrypt(request.getText()));
    }

    @PostMapping("/damo/decrypt")
    public ResponseEntity<?> damoDecrypt(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.damoDecrypt(request.getText()));
    }

    @PostMapping("/encryption-manager/encrypt")
    public ResponseEntity<?> encryptionManagerEncrypt(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.encryptionManagerEncrypt(request.getText()));
    }

    @PostMapping("/encryption-manager/decrypt")
    public ResponseEntity<?> encryptionManagerDecrypt(@RequestBody ToolsTextRequestDTO request) {
        return respond(() -> toolsService.encryptionManagerDecrypt(request.getText()));
    }

    @GetMapping("/encryption-manager/status")
    public ResponseEntity<?> encryptionManagerStatus() {
        return respond(() -> toolsService.encryptionManagerStatus());
    }

    @GetMapping("/version")
    public ResponseEntity<?> getVersionInfo() {
        Map<String, Object> result = new HashMap<>();
        try {
            VersionInfoDTO versionInfo = toolsService.getVersionInfo();
            if (versionInfo == null) {
                result.put("success", false);
                result.put("message", "version.info 파일이 없습니다. gradle의 generateVersionInfo 태스크(또는 build) 실행 후 재기동하세요.");
            } else {
                result.put("success", true);
                result.put("data", versionInfo);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return ResponseEntity.ok().contentType(APPLICATION_JSON_UTF8).body(result);
    }

    private ResponseEntity<?> respond(Callable<Object> action) {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            result.put("data", action.call());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return ResponseEntity.ok().contentType(APPLICATION_JSON_UTF8).body(result);
    }
}
