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 연동 암호화.
 *
 * 사용법: DJBErpEncryt(plainText, moduleName) DJBErpEncryt(plainText, moduleName,
 * groupSeq)
 *
 * 파라미터: plainText : 암호화할 평문 (String) moduleName : DB에 등록된 암호화 모듈명 (String)
 * groupSeq : 키 도출용 그룹 시퀀스 (String, 선택). 미전달 시 빈 context로 호출.
 *
 * 반환값: Base64 인코딩된 암호문 (String)
 */
public class DJBEncrypt extends PostfixMathCommand {

	public DJBEncrypt() {
		numberOfParameters = -1;
	}

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

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

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

		try {
			byte[] cipherBytes = CryptoModuleService.getInstance().encrypt(moduleName, new HashMap<>(), null,
					plainText.getBytes(StandardCharsets.UTF_8));
			inStack.push(Base64.getEncoder().encodeToString(cipherBytes));
		} catch (ParseException e) {
			throw e;
		} catch (Exception e) {
			throw new ParseException("DJBErpEncryt 암호화 실패: " + e.getMessage());
		}
	}
}
