package com.eactive.eai.rms.onl.manage.crypto;

import java.time.LocalDateTime;

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 com.eactive.eai.data.entity.onl.security.CryptoModuleConfig;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.data.entity.onl.security.CryptoModuleConfigDataService;
import com.eactive.eai.rms.onl.common.exception.BizException;

@Service
@Transactional
public class CryptoModuleConfigManService extends BaseService {

	private final CryptoModuleConfigDataService dataService;
	private final CryptoModuleConfigUiMapper mapper;

	@Autowired
	public CryptoModuleConfigManService(CryptoModuleConfigDataService dataService,
			CryptoModuleConfigUiMapper mapper) {
		this.dataService = dataService;
		this.mapper = mapper;
	}

	public Page<CryptoModuleConfigUI> selectList(Pageable pageable, String searchName,
			String algType, String keySourceType, String useYn) {
		Page<CryptoModuleConfig> page = dataService.findAll(pageable, searchName, algType, keySourceType, useYn);
		return page.map(mapper::toVo);
	}

	public CryptoModuleConfigUI selectDetail(String cryptoId) {
		CryptoModuleConfig entity = dataService.findById(cryptoId)
				.orElseThrow(() -> new BizException("암호화 모듈을 찾을 수 없습니다: " + cryptoId));
		return mapper.toVo(entity);
	}

	public String insert(CryptoModuleConfigUI ui, String loginId) {
		CryptoModuleConfig entity = mapper.toEntity(ui);
		entity.setCryptoId(null);
		entity.setModifiedBy(loginId);
		entity.setModifiedAt(LocalDateTime.now());
		dataService.save(entity);
		return entity.getCryptoId();
	}

	public void update(CryptoModuleConfigUI ui, String loginId) {
		CryptoModuleConfig entity = dataService.findById(ui.getCryptoId())
				.orElseThrow(() -> new BizException("암호화 모듈을 찾을 수 없습니다: " + ui.getCryptoId()));
		mapper.updateToEntity(ui, entity);
		entity.setModifiedBy(loginId);
		entity.setModifiedAt(LocalDateTime.now());
		dataService.save(entity);
	}

	public void delete(String cryptoId) {
		dataService.deleteById(cryptoId);
	}

}
