package com.eactive.eai.manage.crypto;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

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

import com.eactive.eai.common.security.CryptoModuleDiagnosticDTO;

/**
 * 암호화모듈(CryptoModuleManager) 진단 및 암복호화 테스트 API.
 *
 * 원본 암호키(encKey/decKey/ivHex)는 응답에 포함하지 않는다. 메타데이터와
 * 키 도출 전략(KeyDerivationStrategy) 로드 상태만 노출한다.
 *
 * GET  /manage/crypto/list                     → 등록된 전체 암호화모듈 진단정보
 * GET  /manage/crypto/{cryptoName}              → 단일 암호화모듈 진단정보
 * GET  /manage/crypto/cache/dynamic-keys        → 동적 키 캐시 키 목록 (원본 키 아님)
 * POST /manage/crypto/{cryptoName}/test/encrypt → 테스트 암호화 (Base64 입출력)
 * POST /manage/crypto/{cryptoName}/test/decrypt → 테스트 복호화 (Base64 입출력)
 */
@RestController
@RequestMapping("/manage/crypto")
public class CryptoModuleManageController {

    @Autowired
    private CryptoModuleManageService cryptoModuleManageService;

    @GetMapping("/list")
    public ResponseEntity<?> listAll() {
        List<CryptoModuleDiagnosticDTO> list = cryptoModuleManageService.listAll();
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", list);
        result.put("count", list.size());
        return ResponseEntity.ok(result);
    }

    @GetMapping("/{cryptoName}")
    public ResponseEntity<?> get(@PathVariable String cryptoName) {
        return respond(() -> cryptoModuleManageService.get(cryptoName));
    }

    @GetMapping("/cache/dynamic-keys")
    public ResponseEntity<?> listDynamicCacheKeys() {
        List<String> keys = cryptoModuleManageService.listDynamicCacheKeys();
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("data", keys);
        result.put("count", keys.size());
        return ResponseEntity.ok(result);
    }

    @PostMapping("/{cryptoName}/test/encrypt")
    public ResponseEntity<?> testEncrypt(@PathVariable String cryptoName, @RequestBody CryptoTestRequestDTO request) {
        return respond(() -> {
            String cipherTextBase64 = cryptoModuleManageService.testEncrypt(cryptoName,
                    request.getRuntimeContext(), request.getPlainTextBase64(), request.getAadBase64());
            Map<String, Object> data = new HashMap<>();
            data.put("cipherTextBase64", cipherTextBase64);
            return data;
        });
    }

    @PostMapping("/{cryptoName}/test/decrypt")
    public ResponseEntity<?> testDecrypt(@PathVariable String cryptoName, @RequestBody CryptoTestRequestDTO request) {
        return respond(() -> {
            String plainTextBase64 = cryptoModuleManageService.testDecrypt(cryptoName,
                    request.getRuntimeContext(), request.getCipherTextBase64(), request.getAadBase64());
            Map<String, Object> data = new HashMap<>();
            data.put("plainTextBase64", plainTextBase64);
            return data;
        });
    }

    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(result);
    }
}
