package com.eactive.eai.rms.onl.apim.approval.credential;

import com.eactive.apim.portal.app.entity.Credential;
import com.eactive.apim.portal.app.entity.QCredential;
import com.eactive.eai.data.jpa.AbstractDataService;
import com.querydsl.core.types.dsl.BooleanExpression;
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;

@Service
@Transactional
public class CredentialService extends AbstractDataService<Credential, String, CredentialEMSRepository> {

    public Page<Credential> findAll(Pageable pageable, CredentialSearch clientSearch) {
        QCredential qClientEntity = QCredential.credential;

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

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

        if (StringUtils.isNotBlank(clientSearch.getSearchOrgId())) {
            predicate = predicate.and(qClientEntity.orgid.eq(clientSearch.getSearchOrgId()));
        }

        return repository.findAll(predicate, pageable);
    }

    /**
     * clientId와 orgId로 Credential 조회
     *
     * @param clientId 클라이언트 ID
     * @param orgId 조직 ID
     * @return Credential 또는 null
     */
    public Credential findByClientidAndOrgid(String clientId, String orgId) {
        QCredential qCredential = QCredential.credential;
        BooleanExpression predicate = qCredential.clientid.eq(clientId)
                .and(qCredential.orgid.eq(orgId));
        return repository.findOne(predicate).orElse(null);
    }
}
