package com.eactive.eai.rms.onl.apim.messagerequest;

import com.eactive.apim.portal.template.entity.MessageCode;
import com.eactive.apim.portal.template.entity.MessageRequest;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.data.entity.onl.apim.messagerequest.MessageRequestUISearch;
import com.eactive.eai.rms.onl.apim.masking.MaskingUtils;
import com.eactive.eai.rms.onl.apim.masking.MessagePatternMaskingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class MessageRequestManService extends BaseService {

	// KST 한글 요일 포맷 (표시용 / 툴팁용)
	private static final DateTimeFormatter FMT_SHORT = DateTimeFormatter.ofPattern("MM-dd(E) HH:mm", Locale.KOREA);
	private static final DateTimeFormatter FMT_FULL = DateTimeFormatter.ofPattern("yyyy-MM-dd (EEE) HH:mm:ss", Locale.KOREA);

	private final com.eactive.eai.rms.data.entity.onl.apim.messagerequest.MessageRequestService messageRequestService;

	@Autowired
	public MessageRequestManService(com.eactive.eai.rms.data.entity.onl.apim.messagerequest.MessageRequestService messageRequestService) {
		this.messageRequestService = messageRequestService;
	}

	public Page<MessageRequestUI> selectList(Pageable pageable, MessageRequestUISearch search) {
		return messageRequestService.findAll(pageable, search).map(this::convertToUI);
	}

	public MessageRequestUI selectDetail(String id) {
		return convertToUI(messageRequestService.getById(id));
	}

	/** PENDING → FAILED 전환. */
	public void updateStatusToFailed(String id) {
		messageRequestService.updateStatusToFailedIfPending(id);
	}

	/** 엔티티 → 마스킹/포맷 적용된 UI 변환 (목록·상세 공통). */
	private MessageRequestUI convertToUI(MessageRequest e) {
		MessageRequestUI ui = new MessageRequestUI();
		ui.setId(e.getId());
		ui.setMessageCode(e.getMessageCode() != null ? e.getMessageCode().name() : null);
		ui.setMessageCodeName(e.getMessageCode() != null ? e.getMessageCode().getDescription() : null);
		ui.setSubject(e.getSubject());
		ui.setMessageType(e.getMessageType());

		// 본문: 패턴 마스킹 + 색상강조 안전 HTML
		ui.setMessageHtml(MessagePatternMaskingUtils.maskAndHighlight(e.getMessage()));

		// 수신자 마스킹 (email/phone 은 @Convert 로 이미 복호화된 평문)
		ui.setUsername(MaskingUtils.maskName(e.getUsername()));
		ui.setEmail(MaskingUtils.maskEmailId(e.getEmail()));
		ui.setPhone(MaskingUtils.maskPhoneNumber(e.getPhone()));
		ui.setMessengerId(MessagePatternMaskingUtils.maskMessengerId(e.getMessengerId()));

		ui.setUmsUid(e.getUmsUid());
		ui.setRequestStatus(e.getRequestStatus());
		ui.setEaiInterfaceId(e.getEaiInterfaceId());
		ui.setServiceId(e.getServiceId());

		ui.setRequestDateShort(fmt(e.getRequestDate(), FMT_SHORT));
		ui.setRequestDateFull(fmt(e.getRequestDate(), FMT_FULL));
		ui.setSentDateShort(fmt(e.getSentDate(), FMT_SHORT));
		ui.setSentDateFull(fmt(e.getSentDate(), FMT_FULL));
		return ui;
	}

	private static String fmt(LocalDateTime t, DateTimeFormatter f) {
		return t == null ? "" : t.format(f);
	}

	/** 상태 검색 콤보 (PENDING/SENT/FAILED). */
	public List<ComboVo> statusCombo() {
		return Arrays.stream(new String[]{"PENDING", "SENT", "FAILED"})
				.map(s -> {
					ComboVo v = new ComboVo();
					v.setCode(s);
					v.setCodename(s);
					return v;
				}).collect(Collectors.toList());
	}

	/** 메세지 코드 검색 콤보 (enum name → 한글 설명). */
	public List<ComboVo> messageCodeCombo() {
		return Arrays.stream(MessageCode.values())
				.map(c -> {
					ComboVo v = new ComboVo();
					v.setCode(c.name());
					v.setCodename(c.getDescription());
					return v;
				}).collect(Collectors.toList());
	}
}
