package com.eactive.eai.rms.data.entity.onl.authserver;

import com.eactive.eai.data.entity.onl.message.EAIMessageEntity;
import org.apache.commons.lang3.StringUtils;
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.authserver.ClientEntity;
import com.eactive.eai.data.entity.onl.authserver.QClientEntity;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.types.dsl.BooleanExpression;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class ClientEntityService extends AbstractDataService<ClientEntity, String, ClientEntityEMSRepository> {

	public Page<ClientEntity> findAll(Pageable pageable, ClientSearch clientSearch) {
		QClientEntity qClientEntity = QClientEntity.clientEntity;

		BooleanExpression predicate = qClientEntity.clientname.containsIgnoreCase(clientSearch.getSearchClientName());

		if (StringUtils.isNotBlank(clientSearch.getSearchClientId())) {
			predicate = predicate.and(qClientEntity.clientid.containsIgnoreCase(clientSearch.getSearchClientId()));
		}

		return repository.findAll(predicate, pageable);
	}

	public List<String> deleteApiByEaiSvcName(String eaiSvcName) {
		List<String> affectedClientIds = new ArrayList<>();
		List<ClientEntity> clientEntities = repository.findAll();
		for (ClientEntity clientEntity : clientEntities) {
			List<EAIMessageEntity> apiList = clientEntity.getApiList();
			boolean removed = apiList.removeIf(api -> api.getEaisvcname().equals(eaiSvcName));
			if (removed) {
				affectedClientIds.add(clientEntity.getClientid());
				repository.save(clientEntity);
			}
		}
		return affectedClientIds;
	}
}
