package com.eactive.eai.rms.onl.manage.authserver.scope;

import java.util.List;

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.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.spring.LocaleMessage;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeEntityService;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeInfo;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeInfoService;
import com.eactive.eai.rms.data.entity.onl.authserver.ScopeSearch;
import com.eactive.eai.rms.onl.common.exception.BizException;

@Service
@Transactional
public class ScopeManService extends OnlBaseService {

	private ScopeInfoService scopeInfoService;

	private ScopeEntityService scopeEntityService;

	private ScopeUIMapper scopeUIMapper;

	private ApiScopeUIMapper apiScopeUIMapper;

	private LocaleMessage localeMessage;

	@Autowired
	public ScopeManService(ScopeInfoService scopeInfoService, ScopeEntityService scopeEntityService,
			ScopeUIMapper scopeUIMapper, ApiScopeUIMapper apiScopeUIMapper, LocaleMessage localeMessage ) {
		this.scopeInfoService = scopeInfoService;
		this.scopeEntityService = scopeEntityService;
		this.scopeUIMapper = scopeUIMapper;
		this.apiScopeUIMapper = apiScopeUIMapper;
		this.localeMessage = localeMessage;
	}

	public Page<ScopeUI> selectList(Pageable pageable, ScopeSearch scopeSearch) {
		Page<ScopeInfo> page = scopeInfoService.findAll(pageable, scopeSearch);
		return page.map(scopeUIMapper::toVo);
	}

	public ScopeUI selectDetail(String scopeId) {
		return scopeUIMapper.toVo(scopeInfoService.getById(scopeId));
	}

	public void insert(ScopeUI scopeUI) {
		if(scopeInfoService.existsById(scopeUI.getScopeId())) {
			throw new BizException(localeMessage.getString("scpMan.scpIdExists"));
		}
		ScopeInfo scopeInfo = scopeUIMapper.toEntity(scopeUI);
		scopeInfoService.save(scopeInfo);
	}

	public void update(ScopeUI scopeUI) {
		ScopeInfo scopeInfo = scopeInfoService.getById(scopeUI.getScopeId());
		scopeUIMapper.updateToEntity(scopeUI, scopeInfo);
		scopeInfoService.save(scopeInfo);
	}

	public void delete(String scopeId) {
		scopeInfoService.deleteById(scopeId);
	}
	
	public void deleteApiScopeRelationsByScopeId(String scopeId) {
		scopeEntityService.deleteByIdScopeId(scopeId);
	}

	public void updateApiScopeRelations(List<ApiScopeUI> apiScopeList, String scopeId) {
		if (scopeId == null || scopeId.isEmpty()) {
			throw new BizException("ScopeId 가 존재하지 않습니다.");
		}

		// ScopeId 기준 전체 삭제 후 LIST 기준으로 재저장.
		scopeEntityService.deleteByIdScopeId(scopeId);

		if (apiScopeList == null || apiScopeList.isEmpty()) {
			return;
		}

		for (ApiScopeUI ui : apiScopeList) {
			ui.setScopeId(scopeId);
			scopeEntityService.save(apiScopeUIMapper.toEntity(ui));
		}
	}

}
