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

import com.eactive.apim.portal.file.entity.FileInfo;
import com.eactive.apim.portal.file.service.FileService;
import com.eactive.apim.portal.partnershipapplication.entity.PartnershipApplication;
import com.eactive.apim.portal.portaluser.entity.PortalUser;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.apim.portalpartnerslhip.PortalPartnershipService;
import com.eactive.eai.rms.data.entity.onl.apim.portaluser.PortalUserService;
import com.eactive.eai.rms.onl.apim.masking.MaskingUtils;
import org.apache.commons.lang3.StringUtils;
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.util.Arrays;
import java.util.List;
import java.util.Optional;

@Service
@Transactional(transactionManager = "transactionManagerForEMS")
public class PortalPartnershipManService extends BaseService {
	private final PortalPartnershipService partnershipService;
	private final PortalPartnershipUIMapper portalPartnershipUIMapper;
	private final PortalUserService portalUserService;
	private final FileService fileService;

	@Autowired
	public PortalPartnershipManService(PortalPartnershipService partnershipService,
									   PortalPartnershipUIMapper portalPartnershipUIMapper,
									   PortalUserService portalUserService, FileService fileService){
		this.partnershipService = partnershipService;
		this.portalPartnershipUIMapper = portalPartnershipUIMapper;
		this.portalUserService = portalUserService;
		this.fileService = fileService;
	}

	private PortalUser findUser(String createdBy) {
		return portalUserService.findByUserId(createdBy);
	}
	public Page<PortalPartnershipUI> selectList(Pageable pageable, String searchBizSubject, String searchBizDetail) {
		return partnershipService.findAll(pageable, searchBizSubject, searchBizDetail)
				.map(entity -> convertToUIWithMaskOption(entity, true));
	}

	public PortalPartnershipUI selectDetail(String id) {
		PartnershipApplication partnershipApplication = partnershipService.getById(id);
		return convertToUIWithMaskOption(partnershipApplication, true);
	}

	public PortalPartnershipUI selectDetailUnmask(String id) {
		PartnershipApplication partnershipApplication = partnershipService.getById(id);
		return convertToUIWithMaskOption(partnershipApplication, false);
	}

	public void delete(String id) {
		PartnershipApplication partnership = partnershipService.getById(id);
		Optional.ofNullable(partnership.getFileId())
				.filter(StringUtils::isNotBlank)
				.ifPresent(fileService::deleteFile);
		partnershipService.deleteById(id);
	}

	public void deleteBulk(String ids) {
		if (StringUtils.isBlank(ids)) {
			return;
		}

		List<String> idList = Arrays.asList(ids.split(","));

		// 첨부파일 정리 (단건 삭제와 동일한 처리)
		idList.forEach(id -> {
			PartnershipApplication partnership = partnershipService.getById(id);
			Optional.ofNullable(partnership.getFileId())
					.filter(StringUtils::isNotBlank)
					.ifPresent(fileService::deleteFile);
		});

		partnershipService.deleteByIds(idList);
	}

	private PortalPartnershipUI convertToUIWithMaskOption(PartnershipApplication partnership, boolean isMasked) {
		PortalPartnershipUI partnershipUI = portalPartnershipUIMapper.toVo(partnership);
		PortalUser user = findUser(partnership.getCreatedBy());

		// 작성자(createdBy)에 해당하는 포털 사용자가 없을 수 있음(탈퇴/삭제, 시스템 작성 등)
		String userName = user != null ? user.getUserName() : null;
		String loginId = user != null ? user.getLoginId() : null;

		if (isMasked) {
			// 마스킹 처리
			partnershipUI.setCreatedByName(MaskingUtils.maskName(userName));
			partnershipUI.setCreatedById(MaskingUtils.maskEmailId(loginId));
		} else {
			// 마스킹 해제 상태
			partnershipUI.setCreatedByName(userName);
			partnershipUI.setCreatedById(loginId);
		}

		// 첨부파일 처리
		if (StringUtils.isNotBlank(partnership.getFileId())) {
			FileInfo fileInfo = fileService.findById(partnership.getFileId());
			partnershipUI.setFileInfo(fileInfo);
			partnershipUI.setHasAttachment(true);
		} else {
			partnershipUI.setHasAttachment(false);
		}

		return partnershipUI;
	}

}
