package com.eactive.eai.rms.onl.transaction.simpleinterface;

import com.eactive.eai.adapter.Keys;
import com.eactive.eai.data.entity.onl.message.EAIMessageEntity;
import com.eactive.eai.data.entity.onl.message.QEAIMessageEntity;
import com.eactive.eai.data.entity.onl.message.ServiceMessageEntity;
import com.eactive.eai.data.entity.onl.messagekey.MessageKey;
import com.eactive.eai.data.entity.onl.stdmessage.StandardMessageInfo;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.data.entity.onl.eaimsg.EAIMessageService;
import com.eactive.eai.rms.data.entity.onl.eaimsg.EAIMessageUISearch;
import com.eactive.eai.rms.data.entity.onl.eaimsg.ServiceMessageService;
import com.eactive.eai.rms.data.entity.onl.layout.LayoutService;
import com.eactive.eai.rms.data.entity.onl.messagekey.MessageKeyService;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.adapter.adapter.AdapterManService;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterPropUI;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterUI;
import com.eactive.eai.rms.onl.transaction.apim.BizCodeQueryServiceForApi;
import com.eactive.eai.rms.onl.transaction.apim.StandardMessageInfoQueryServiceForApi;
import com.eactive.eai.rms.onl.transaction.apim.mapping.BizCodeMapper;
import com.eactive.eai.rms.onl.transaction.apim.vo.BizCodeVo;
import com.eactive.eai.rms.onl.transaction.apim.vo.RestOption;
import com.eactive.eai.rms.onl.transaction.simpleinterface.mapping.SimpleInterfaceUIMapper;
import com.eactive.eai.rms.onl.transaction.simpleinterface.ui.SimpleInterfaceUI;
import com.eactive.eai.transformer.transform.loader.TransformLoader;
import com.eactive.eai.transformer.util.Logger;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.querydsl.core.Tuple;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@Transactional
@Repository
public class SimpleInterfaceService extends OnlBaseService {

	private static final Logger logger = Logger.getLogger(SimpleInterfaceService.class);

	public static final String STEMSG_SERVICE_URL_DELIMITER = "|";

	public static final String STEMSG_METHOD_DELIMITER = ":";

	public static final String STEMSG_SERVICE_HEADER_DELIMITER = "^";

	public static final String STEMSG_HEADER_SEPARATOR = ";";

	@Autowired
	MessageKeyService messageKeyService;

	@Autowired
	private SimpleInterfaceUIMapper simpleInterfaceUIMapper;

	@Autowired
	private EAIMessageService eaiMessageQueryService;

	@Autowired
	private ServiceMessageService serviceMessageQueryService;

	@Autowired
	private StandardMessageInfoQueryServiceForApi standardMessageInfoQueryService;

	@Autowired
	private AdapterManService adapterService;

	@Autowired
	private LayoutService layoutService;

	@Autowired
	private TransformLoader transformLoader;

	@Autowired
	private ComboService comboService;

	@Autowired
	private BizCodeMapper bizCodeMapper;

	@Autowired
	private BizCodeQueryServiceForApi bizCodeQueryServiceForApi;

	@Transactional
	public Page<SimpleInterfaceUI> selectList(EAIMessageUISearch eaiMessageUISearch, Pageable pageable, String sortname,  String sortorder) {
		Page<Tuple> tuples = eaiMessageQueryService.selectList(eaiMessageUISearch, pageable, sortname, sortorder);

		return tuples.map(tuple -> {
			EAIMessageEntity eaiMessageEntity = tuple.get(QEAIMessageEntity.eAIMessageEntity);

			SimpleInterfaceUI simpleInterfaceUI;
			if(eaiMessageEntity.getServiceMessages() != null && eaiMessageEntity.getServiceMessages().size() > 0){
				simpleInterfaceUI = simpleInterfaceUIMapper.toVo(eaiMessageEntity, eaiMessageEntity.getServiceMessages().get(0));
			}else{
				simpleInterfaceUI = simpleInterfaceUIMapper.toVo(eaiMessageEntity);
			}

			return simpleInterfaceUI;
		});
	}

	public HashMap selectCombo(String userId) throws Exception {

		List<BizCodeVo> voList = bizCodeMapper.toVoList(bizCodeQueryServiceForApi.selectUserBizCodes(userId));
		// 전체 목록수 얻기
		HashMap map = new HashMap();
		map.put("bizList", voList);

		return map;
	}

	@Transactional
	public SimpleInterfaceUI selectDetail(String eaiSvcName) throws Exception {
		EAIMessageEntity eaiMessageEntity = eaiMessageQueryService.findById(eaiSvcName).get();
		SimpleInterfaceUI simpleInterfaceUI;
		ServiceMessageEntity serviceMessageEntity = null;
		List<ServiceMessageEntity> serviceMessageEntityList = eaiMessageEntity.getServiceMessages();
		if(serviceMessageEntityList != null && serviceMessageEntityList.size() > 0){
			serviceMessageEntity = serviceMessageEntityList.get(0);
			simpleInterfaceUI = simpleInterfaceUIMapper.toVo(eaiMessageEntity, serviceMessageEntity);
		}else{
			simpleInterfaceUI = simpleInterfaceUIMapper.toVo(eaiMessageEntity);
		}

			// 레이아웃 이름 설정
		setLayoutNames(simpleInterfaceUI, eaiMessageEntity.getEaibzwkdstcd(), eaiSvcName);
		String transformYn = "N";

		if(serviceMessageEntity != null){
			String requestTranform = serviceMessageEntity.getChngmsgidname();
			simpleInterfaceUI.setRequestTransform(requestTranform);
			String responseTranform = serviceMessageEntity.getBascrspnschngmsgidname();
			simpleInterfaceUI.setResponseTransform(responseTranform);

			if("1".equals(serviceMessageEntity.getChngeonot()) || "1".equals(serviceMessageEntity.getBascrspnschngeonot()) ){// 요청이나 응답 변환 여부
				transformYn = "Y";
			}

			String restOptionStr = serviceMessageEntity.getRestoption();

			if(StringUtils.isNotBlank(restOptionStr)) {
				ObjectMapper mapper = new ObjectMapper();
				RestOption restOption = mapper.readValue(restOptionStr, RestOption.class);

				simpleInterfaceUI.setOutboundHttpMethod(restOption.getMethod());
				simpleInterfaceUI.setOutboundRestPath(restOption.getExtraPath());
			}
		}

		if("asyncSync".equals(simpleInterfaceUI.getSyncAsyncType()) && serviceMessageEntityList.size() > 1){
			ServiceMessageEntity extraServiceMessageEntity = serviceMessageEntityList.get(1);
			simpleInterfaceUI.setFromResponseAdapter(extraServiceMessageEntity.getPsvsysadptrbzwkgroupname());
			String restOptionStr = extraServiceMessageEntity.getRestoption();

			if(StringUtils.isNotBlank(restOptionStr)) {
				ObjectMapper mapper = new ObjectMapper();
				RestOption restOption = mapper.readValue(restOptionStr, RestOption.class);

				simpleInterfaceUI.setInboundResponseHttpMethod(restOption.getMethod());
				simpleInterfaceUI.setInboundResponseRestPath(restOption.getExtraPath());
			}
		}

		simpleInterfaceUI.setTransformYn(transformYn);

		Optional<StandardMessageInfo> optional = standardMessageInfoQueryService.findByEaiSvcName(eaiSvcName);
		if(optional.isPresent()){
			StandardMessageInfo standardMessageInfo = optional.get();
			String stdKey = standardMessageInfo.getBzwksvckeyname();
			String inboundRestPath = StringUtils.substringAfter(stdKey, STEMSG_SERVICE_URL_DELIMITER);
			simpleInterfaceUI.setInboundRestPath(inboundRestPath);

			String inboundHttpMethod;
			if(StringUtils.contains(stdKey, STEMSG_SERVICE_HEADER_DELIMITER)){
				inboundHttpMethod = StringUtils.substringBetween(stdKey, STEMSG_METHOD_DELIMITER, STEMSG_SERVICE_HEADER_DELIMITER);
				String headerRoutingValueString = StringUtils.substringAfter(stdKey, STEMSG_SERVICE_HEADER_DELIMITER);

				List<String> headerValues = new ArrayList<>();
				String[] values = headerRoutingValueString.split(SimpleInterfaceService.STEMSG_HEADER_SEPARATOR);

				for (String value : values) {
					headerValues.add(value);
				}
				simpleInterfaceUI.setHeaderValues(headerValues);
			}else {
				inboundHttpMethod = StringUtils.substringBetween(stdKey, STEMSG_METHOD_DELIMITER, STEMSG_SERVICE_URL_DELIMITER);
			}

			simpleInterfaceUI.setInboundHttpMethod(inboundHttpMethod == null ?  "" :inboundHttpMethod.toLowerCase());
		}

		if("syncAsync".equals(simpleInterfaceUI.getSyncAsyncType()) && StringUtils.isNotBlank(eaiSvcName) && eaiSvcName.charAt(eaiSvcName.length() - 2) == 'S') {
			String recvEaiSvcName = simpleInterfaceUIMapper.changeEaiSvcNameToRecv(eaiSvcName);
			EAIMessageEntity recvEaiMessageEntity = eaiMessageQueryService.getById(recvEaiSvcName);
			simpleInterfaceUI.setToResponseAdapter(recvEaiMessageEntity.getGstatsysadptrbzwkgroupname());

			optional = standardMessageInfoQueryService.findByEaiSvcName(recvEaiSvcName);
			if(optional.isPresent()){
				StandardMessageInfo standardMessageInfo = optional.get();
				String stdKey = standardMessageInfo.getBzwksvckeyname();
				String restPath = StringUtils.substringAfter(stdKey, STEMSG_SERVICE_URL_DELIMITER);
				simpleInterfaceUI.setOutboundResponseRestPath(restPath);
				String httpMethod = StringUtils.substringBetween(stdKey, STEMSG_METHOD_DELIMITER, STEMSG_SERVICE_URL_DELIMITER);
				simpleInterfaceUI.setOutboundResponseHttpMethod(httpMethod == null ?  "" :httpMethod.toLowerCase());
			}
		}

		return simpleInterfaceUI;
	}

	private void setLayoutNames(SimpleInterfaceUI simpleInterfaceUI, String bzcd, String eaiSvcName) {
		String[] types = {"SRCS", "TGTS", "TGTR", "SRCR"};
		for (String type : types) {
			String layoutName = bzcd + "_" + eaiSvcName + "_" + type;
			boolean hasLayout = layoutService.findById(layoutName).isPresent();
			if (hasLayout) {
				// 각 타입에 대한 서로 다른 속성을 설정한다고 가정
				// 실제 setter에 맞게 이 부분을 업데이트하세요
				switch (type) {
					case "SRCS":
						simpleInterfaceUI.setInboundRequestLayout(layoutName);
						break;
					case "TGTS":
						simpleInterfaceUI.setOutboundRequestLayout(layoutName);
						break;
					case "TGTR":
						simpleInterfaceUI.setOutboundResponseLayout(layoutName);
						break;
					case "SRCR":
						simpleInterfaceUI.setInboundResponseLayout(layoutName);
						break;
				}
			}
		}
	}

	@Transactional
	public HashMap selectDetailCombo(String userId) throws Exception {
		HashMap paramMap = new HashMap();
		paramMap.put("userId", userId);

		//업무구분
		List<BizCodeVo> listBiz = bizCodeMapper.toVoList(bizCodeQueryServiceForApi.selectUserBizCodes(userId));
		//당타발구분
		List<ComboVo> listIo = comboService.getFromCode("IO_TYPE");
		//전문요청구분
		List listReqRes = comboService.getFromCode("REQRES_TYPE");
		//송수신방법
		List listSyncAsync = comboService.getFromCode("SYNCASYNC_TYPE");
		//거래흐름(INBOUND);
		List<AdapterGroupUI> listFrom = adapterService.selectListComboForAdptrIoDstcd("IN");
		//거래흐름(OUTBOUND);
		List<AdapterGroupUI> listTo = adapterService.selectListComboForAdptrIoDstcd("OU");

		Map<String, List<String>> fromAdapterMessageKeyMap = new HashMap<>();

		listFrom.forEach(adapterGroup -> {
			String adapterGroupName = adapterGroup.getAdptrbzwkgroupname();
			List<String> messageKeyGroup = getFirstBzwkfldnameListsByGroup(adapterGroupName);
			if(messageKeyGroup != null && messageKeyGroup.size() > 0){
				fromAdapterMessageKeyMap.put(adapterGroupName, messageKeyGroup);
			}
		});

		HashMap map = new HashMap();

		map.put("bizList", listBiz);
		map.put("ioList", listIo);
		map.put("reqResList", listReqRes);
		map.put("syncAsyncList", listSyncAsync);
		map.put("fromList", listFrom);
		map.put("fromAdapterMessageKeyMap", fromAdapterMessageKeyMap);
		map.put("toList", listTo);

		return map;
	}

	public HashMap getAdapterUrl(String adapterGroupName) throws Exception {
		AdapterGroupUI adapterGroup = adapterService.selectDetail(adapterGroupName);
		String adptriodstcd = adapterGroup.getAdptriodstcd();
		StringBuilder urlPathBuilder = new StringBuilder();

		for(AdapterUI adapter : adapterGroup.getAdapters()) {
			String url = null;
			for (AdapterPropUI prop : adapter.getAdapterPropGroup().getAdapterProps()) {
				String propName = "I".equals(adptriodstcd) ? "API_PATH" : "URL";
				if (propName.equals(prop.getPrptyname())) {
					url = prop.getPrpty2val();
					break;
				}
			}

			if (url != null) {
				if (urlPathBuilder.length() > 100) {
					urlPathBuilder.append("...");
					break;
				}
				if (urlPathBuilder.length() > 0) {
					urlPathBuilder.append(", "); // 기존에 문자열이 있다면 쉼표 추가
				}
				urlPathBuilder.append(url); // 새로운 URL 부분 추가
			}
		}
		String urlPath = urlPathBuilder.toString(); // 최종 문자열 얻기

		HashMap<String, String> resultMap = new HashMap<>();
		resultMap.put("urlPath", urlPath);
		return resultMap;
	}

	@Transactional
	public AdapterGroupUI selectAdapterGroupDetail(String adapterGroupName) throws Exception {
		return adapterService.selectDetail(adapterGroupName);
	}

	public List<String> update(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		String eaiSvcName = simpleInterfaceUI.getEaiSvcName();

		EAIMessageEntity eaiMessageEntity = eaiMessageQueryService.getById(eaiSvcName);
		simpleInterfaceUIMapper.updateEaiMessageEntity(simpleInterfaceUI, eaiMessageEntity);
		eaiMessageQueryService.save(eaiMessageEntity);

		List<ServiceMessageEntity> serviceMessageEntityList = eaiMessageEntity.getServiceMessages();

		if(eaiMessageEntity.getServiceMessages().size() > 0){
			ServiceMessageEntity serviceMessageEntity = eaiMessageEntity.getServiceMessages().get(0);
			simpleInterfaceUIMapper.updateServiceMessageEntity(simpleInterfaceUI, serviceMessageEntity);
		}else{
			ServiceMessageEntity serviceMessageEntity = simpleInterfaceUIMapper.toServiceMessageEntity(simpleInterfaceUI);
			serviceMessageEntityList.add(serviceMessageEntity);
		}

		setServiceMessageRoutingInfo(simpleInterfaceUI, eaiMessageEntity, serviceMessageEntityList);

		for(ServiceMessageEntity serviceMessageEntity : serviceMessageEntityList){
			serviceMessageQueryService.save(serviceMessageEntity);
		}

		List<String> standardMessageKeyList = new ArrayList<>();
		standardMessageKeyList.add(mergeStdMessage(simpleInterfaceUI, false));

		if("syncAsync".equals(simpleInterfaceUI.getSyncAsyncType()) && StringUtils.isNotBlank(eaiSvcName) && eaiSvcName.charAt(eaiSvcName.length() - 2) == 'S'){
			String recvEaiSvcName = simpleInterfaceUIMapper.changeEaiSvcNameToRecv(eaiSvcName);
			EAIMessageEntity recvEaiMessageEntity = eaiMessageQueryService.getById(recvEaiSvcName);
			recvEaiMessageEntity.setGstatsysadptrbzwkgroupname(simpleInterfaceUI.getToResponseAdapter());

			eaiMessageQueryService.save(recvEaiMessageEntity);

			standardMessageKeyList.add(mergeStdMessage(simpleInterfaceUI, true));
		}

		return standardMessageKeyList;
	}

	private void setRouterAndRestOption(ServiceMessageEntity serviceMessageEntity, String adapterGroupName, String method, String restPath) throws Exception {
		String restOption = "";
		String outbndRoutName = getRouterByAdapter(adapterGroupName);
		boolean isRestOut = "RESTOUT".equals(outbndRoutName);

		serviceMessageEntity.setOutbndroutname(outbndRoutName);

		if(isRestOut) {
			restOption = getRestOption(method, restPath);
		}
		serviceMessageEntity.setRestoption(restOption);
	}

	private void setServiceMessageRoutingInfo(SimpleInterfaceUI vo, EAIMessageEntity eaiMessageEntity, List<ServiceMessageEntity> serviceMessageEntityList) throws Exception{
		ServiceMessageEntity serviceMessageEntity = serviceMessageEntityList.get(0);
		setRouterAndRestOption(serviceMessageEntity, vo.getToAdapter(), vo.getOutboundHttpMethod(), vo.getOutboundRestPath());

		if("asyncSync".equals(vo.getSyncAsyncType())){
			ServiceMessageEntity asyncResponseServiceMessageEntity;
			if(eaiMessageEntity.getServiceMessages().size() > 1){
				asyncResponseServiceMessageEntity = eaiMessageEntity.getServiceMessages().get(1);
				simpleInterfaceUIMapper.updateAsyncSyncResServiceMessageEntity(vo, serviceMessageEntity);
			}else{
				asyncResponseServiceMessageEntity = simpleInterfaceUIMapper.toAsyncSyncResServiceMessageEntity(vo);
				serviceMessageEntityList.add(asyncResponseServiceMessageEntity);
				asyncResponseServiceMessageEntity.setEaimessage(eaiMessageEntity);
			}
			String fromResponseRoutName = getRouterByAdapter(vo.getFromResponseAdapter());
			asyncResponseServiceMessageEntity.setOutbndroutname(fromResponseRoutName);
			setRouterAndRestOption(asyncResponseServiceMessageEntity, vo.getFromResponseAdapter(), vo.getInboundResponseHttpMethod(), vo.getInboundResponseRestPath());
		}
	}

	private static String getRestOption(String outboundHttpMethod, String outboundRestPath) {
		String restOption;
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("method", outboundHttpMethod);
		jsonObject.put("extraPath", outboundRestPath);

		String pathType = outboundRestPath.matches(".*\\{.+\\}.*") ? "variableUrlRequest" : "simpleRequest";
		jsonObject.put("type", pathType);
		restOption = jsonObject.toString();
		return restOption;
	}

	@NotNull
	private String getRouterByAdapter(String adapterGroupName) throws Exception {
		AdapterGroupUI outboundAdapter = adapterService.selectDetail(adapterGroupName);
		if(outboundAdapter == null){
			throw new Exception("아웃바운드 어댑터 오류입니다.");
		}

		boolean isRestOut = false;
		HashMap<String, Object> paramMap = new HashMap<>();
		String outbndRoutName;
		switch ((String) outboundAdapter.getAdptrcd()){
			case "HTT": outbndRoutName = "HTTPOUT"; break;
			case "NET": outbndRoutName = "SOCKETOUT"; break;
			default:
				outbndRoutName = "RESTOUT";
			break;
		}
		return outbndRoutName;
	}


	public List<String> insert(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		String eaiSvcName = simpleInterfaceUI.getEaiSvcName();

		Optional<EAIMessageEntity> optional = eaiMessageQueryService.findById(eaiSvcName);
		if (optional.isPresent()) {
			String bzwkDstcd = optional.get().getEaibzwkdstcd();
			throw new BizException("업무명[" + bzwkDstcd + "]로 이미 등록된 인터페이스입니다.\n조회가 되지 않을 시 담당자에게 문의바랍니다.");
		}

		EAIMessageEntity eaiMessageEntity = simpleInterfaceUIMapper.toEaiMessageEntity(simpleInterfaceUI);
		ServiceMessageEntity serviceMessageEntity = simpleInterfaceUIMapper.toServiceMessageEntity(simpleInterfaceUI);
		serviceMessageEntity.setEaimessage(eaiMessageEntity);
		List<ServiceMessageEntity> serviceMessageEntityList = new ArrayList<>();
		serviceMessageEntityList.add(serviceMessageEntity);
		eaiMessageEntity.setServiceMessages(serviceMessageEntityList);

		setServiceMessageRoutingInfo(simpleInterfaceUI, eaiMessageEntity, serviceMessageEntityList);

		eaiMessageQueryService.save(eaiMessageEntity);

		List<String> standardMessageKeyList = new ArrayList<>();
		standardMessageKeyList.add(mergeStdMessage(simpleInterfaceUI, false));

		if("syncAsync".equals(simpleInterfaceUI.getSyncAsyncType()) && StringUtils.isNotBlank(eaiSvcName) && eaiSvcName.charAt(eaiSvcName.length() - 2) == 'S'){
			EAIMessageEntity recvEaiMessageEntity = simpleInterfaceUIMapper.toSyncAsyncResEaiMessageEntity(simpleInterfaceUI);
			ServiceMessageEntity recvServiceMessageEntity = simpleInterfaceUIMapper.toSyncAsyncResServiceMessageEntity(simpleInterfaceUI);
			recvServiceMessageEntity.setEaimessage(recvEaiMessageEntity);
			List<ServiceMessageEntity> recvServiceMessageEntityList = new ArrayList<>();
			recvServiceMessageEntityList.add(recvServiceMessageEntity);
			recvEaiMessageEntity.setServiceMessages(recvServiceMessageEntityList);

			setRouterAndRestOption(recvServiceMessageEntity, simpleInterfaceUI.getToResponseAdapter(), simpleInterfaceUI.getOutboundResponseHttpMethod(), simpleInterfaceUI.getOutboundResponseRestPath());

			eaiMessageQueryService.save(recvEaiMessageEntity);

			standardMessageKeyList.add(mergeStdMessage(simpleInterfaceUI, true));
		}

		return standardMessageKeyList;
	}


	public String mergeStdMessage(SimpleInterfaceUI vo, boolean isSyncAsyncResponse) throws Exception {
		logger.info ("내부 표준 전문 INSERT");
		// 내부 표준 전문 INSERT
		// 비표준에서 표준으로 가는 경우 표준으로 전환하기 위한 정보 이므로 내부로 갈 때만 처리
		String inboundAdapterGroupName;
		String eaiServiceName;
		StandardMessageInfo standardMessageInfo;
		if(isSyncAsyncResponse){
			inboundAdapterGroupName = vo.getToResponseAdapter();
			eaiServiceName = simpleInterfaceUIMapper.changeEaiSvcNameToRecv(vo.getEaiSvcName());
			standardMessageInfo = simpleInterfaceUIMapper.toSyncAsyncResStandardMessageInfo(vo);
		}else {
			inboundAdapterGroupName = vo.getFromAdapter();
			eaiServiceName = vo.getEaiSvcName();
			standardMessageInfo = simpleInterfaceUIMapper.toStandardMessageInfo(vo);
		}

		AdapterGroupUI adapterGroup = adapterService.selectDetail(inboundAdapterGroupName);

		if(Keys.IF_STANDARD.equals(adapterGroup.getAdptrmsgptrncd())) {
			throw new RuntimeException("인바운드 어댑터가 표준전문으로 설정되어있습니다.");
		}
		if(!"RST".equals(adapterGroup.getAdptrcd())) {
			throw new RuntimeException("인바운드 어댑터가 타입이 REST가 아닙니다. 타입을 확인하세요");
		}

		standardMessageInfoQueryService.deleteByEaiSvcName(eaiServiceName);
		standardMessageInfoQueryService.save(standardMessageInfo);

		return standardMessageInfo.getBzwksvckeyname();
	}


	public String delete(SimpleInterfaceUI simpleInterfaceUI) throws Exception {
		StandardMessageInfo standardMessageInfo = standardMessageInfoQueryService.findByEaiSvcName(simpleInterfaceUI.getEaiSvcName()).get();

		String eaiSvcName = simpleInterfaceUI.getEaiSvcName();
		if("syncAsync".equals(simpleInterfaceUI.getSyncAsyncType()) && StringUtils.isNotBlank(eaiSvcName) && eaiSvcName.charAt(eaiSvcName.length() - 2) == 'S'){
			StringBuilder sb = new StringBuilder(eaiSvcName);
			// 끝에서 두 번째 문자를 'S'로 변경
			sb.setCharAt(eaiSvcName.length() - 2, 'R');
			String recvEaiSvcName = sb.toString();
			deleteResourcesWithEaiSvcName(recvEaiSvcName);
		}
		deleteResourcesWithEaiSvcName(eaiSvcName);
		deleteIfNotBlank(simpleInterfaceUI.getRequestTransform(), transformLoader::deleteById);
		deleteIfNotBlank(simpleInterfaceUI.getResponseTransform(), transformLoader::deleteById);
		deleteIfNotBlank(simpleInterfaceUI.getInboundRequestLayout(), layoutService::deleteById);
		deleteIfNotBlank(simpleInterfaceUI.getOutboundRequestLayout(), layoutService::deleteById);
		deleteIfNotBlank(simpleInterfaceUI.getInboundResponseLayout(), layoutService::deleteById);
		deleteIfNotBlank(simpleInterfaceUI.getOutboundResponseLayout(), layoutService::deleteById);

		return standardMessageInfo.getBzwksvckeyname();
	}

	private void deleteResourcesWithEaiSvcName(String eaiSvcName) throws Exception {
		if (StringUtils.isNotBlank(eaiSvcName)) {
			eaiMessageQueryService.deleteById(eaiSvcName);
			standardMessageInfoQueryService.deleteByEaiSvcName(eaiSvcName);
		}
	}


	private void deleteIfNotBlank(String value, Consumer<String> deleteFunction) throws Exception {
		if (StringUtils.isNotBlank(value)) {
			deleteFunction.accept(value);
		}
	}

	protected List<String> getFirstBzwkfldnameListsByGroup(String adapterGroupName){
		List<List<String>> messageKeyGroupList = getBzwkfldnameListsByGroup(adapterGroupName);
		if(messageKeyGroupList == null || messageKeyGroupList.size() == 0){
			return null;
		}

		return messageKeyGroupList.get(0);
	}

	protected List<List<String>> getBzwkfldnameListsByGroup(String adapterGroupName){
		List<MessageKey> messageKeys = messageKeyService.findByAdptrBzwkGroupNameAndIoDstcd(adapterGroupName, "I", true);

		// groupinorno 별로 MessageKey 객체들을 그룹화합니다.
		Map<Integer, List<MessageKey>> groupedByGroupNo = messageKeys.stream()
				.collect(Collectors.groupingBy(key -> key.getId().getGroupinorno()));

		List<List<String>> headerNamesLists = new ArrayList<>();
		// 각 그룹별로 bzwkfldname 값을 추출하여 리스트로 만듭니다.
		for (Map.Entry<Integer, List<MessageKey>> entry : groupedByGroupNo.entrySet()) {
			List<MessageKey> groupedKeys = entry.getValue();
			List<String> headerNames = new ArrayList<>();

			for (MessageKey key : groupedKeys) {
				headerNames.add(key.getBzwkfldname());
			}

			headerNamesLists.add(headerNames);
		}

		return headerNamesLists;
	}
}
