package com.eactive.eai.custom.transformer.function;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Stack;

import org.nfunk.jep.ParseException;
import org.nfunk.jep.function.PostfixMathCommand;

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

/**
 * JEP 트랜스포머 함수 — DJB ERP 연동 복호화.
 *
 * 사용법: DJBErpDecryt(encBase64, moduleName)
 *
 * 파라미터: 
 * encBase64 : Base64 인코딩된 암호문 
 * moduleName : DB에 등록된 암호화 모듈명
 *
 * 반환값: 복호화된 평문 (String)
 */
public class DJBDecrypt extends PostfixMathCommand {

	public DJBDecrypt() {
		numberOfParameters = -1;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void run(Stack inStack) throws ParseException {
		checkStack(inStack);

		if (curNumberOfParameters != 2) {
			throw new ParseException("DJBErpDecryt: 파라미터는 2개개여야 합니다 (encBase64, moduleName");
		}

		String moduleName = inStack.pop().toString();
		String encBase64 = inStack.pop().toString();

		try {
			byte[] cipherBytes = Base64.getDecoder().decode(encBase64.trim());
			byte[] plainBytes = CryptoModuleService.getInstance().decrypt(moduleName, new HashMap<>(), null, cipherBytes);
			inStack.push(new String(plainBytes, StandardCharsets.UTF_8));
		} catch (ParseException e) {
			throw e;
		} catch (Exception e) {
			throw new ParseException("DJBErpDecryt 복호화 실패: " + e.getMessage());
		}
	}
}
