package com.eactive.eai.common.security.keyderiv.strategy;

import java.util.Map;

import javax.crypto.SecretKey;

import com.eactive.eai.common.hsm.HsmCryptoService;
import com.eactive.eai.common.hsm.HsmException;
import com.eactive.eai.common.security.keyderiv.KeyDerivationStrategy;
import com.eactive.eai.common.util.ApplicationContextProvider;

/**
 * HSM 마스터키를 이용하는 전략 클래스들의 기본 클래스
 */
public abstract class BaseHsmKeyDerivationStrategy implements KeyDerivationStrategy {

	protected byte[] getHsmKey(Map<String, String> params) throws HsmException {
		String hsmKeyAlias = required(params, PARAM_HSM_KEY_ALIAS);
		return getHsmKey(hsmKeyAlias);
	}

	protected byte[] getHsmKey(String hsmKeyAlias) throws HsmException {
		SecretKey masterKey = hsmCryptoService().getSecretKey(hsmKeyAlias);
		return masterKey.getEncoded();
	}

	protected byte[] getHsmIv(Map<String, String> params) throws HsmException {
		String hsmKeyAlias = required(params, PARAM_HSM_IV_ALIAS);
		return getHsmKey(hsmKeyAlias);
	}

	private String required(Map<String, String> params, String key) {
		String value = params.get(key);
		if (value == null || value.trim().isEmpty()) {
			throw new IllegalArgumentException("key_deriv_params 필수값 누락: " + key);
		}
		return value;
	}

	private HsmCryptoService hsmCryptoService() {
		return ApplicationContextProvider.getContext().getBean(HsmCryptoService.class);
	}
}
