package cokr.xit.ens.modules.common.ctgy.sys.mng.domain.repository;

import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.common.ctgy.sys.mng.domain.OrgMng;
import cokr.xit.ens.modules.common.ctgy.sys.mng.model.OrgMngSearchDTO;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;

import java.util.List;

import static cokr.xit.ens.modules.common.ctgy.sys.mng.domain.QOrgMng.orgMng;

@RequiredArgsConstructor
public class OrgMngRepositoryImpl implements OrgMngRepositoryCustom {

    private final JPAQueryFactory query;

    @Override
    public List<OrgMng> findAllFetchBySearchDTO(OrgMngSearchDTO searchDTO) {
        return query.selectFrom(orgMng)
                .where(eqSearchDTO(searchDTO))
                .fetch();
    }

    private BooleanBuilder eqSearchDTO(OrgMngSearchDTO searchDTO) {
        BooleanBuilder builder = new BooleanBuilder();

        if (!CmmnUtil.isEmpty(searchDTO.getSchOrgCd()))
            builder.and(orgMng.orgCd.eq(searchDTO.getSchOrgCd()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchOrgNm()))
            builder.and(orgMng.orgNm.like(searchDTO.getSchOrgNm() + "%"));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoMdAccessToken()))
            builder.and(orgMng.kkoMdAccessToken.eq(searchDTO.getSchKkoMdAccessToken()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoMdContractUuid()))
            builder.and(orgMng.kkoMdContractUuid.eq(searchDTO.getSchKkoMdContractUuid()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoBpBillerCode()))
            builder.and(orgMng.kkoBpBillerCode.eq(searchDTO.getSchKkoBpBillerCode()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoBpAuthorization()))
            builder.and(orgMng.kkoBpAuthorization.eq(searchDTO.getSchKkoBpAuthorization()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoAtBsid()))
            builder.and(orgMng.kkoAtBsid.eq(searchDTO.getSchKkoAtBsid()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoAtPasswd()))
            builder.and(orgMng.kkoAtPasswd.eq(searchDTO.getSchKkoAtPasswd()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchKkoAtSenderKey()))
            builder.and(orgMng.kkoAtSenderKey.eq(searchDTO.getSchKkoAtSenderKey()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchNiceCdSiteCode()))
            builder.and(orgMng.niceCdSiteCode.eq(searchDTO.getSchNiceCdSiteCode()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchNiceCdSitePw()))
            builder.and(orgMng.niceCdSitePw.eq(searchDTO.getSchNiceCdSitePw()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchNvStXNaverClientId()))
            builder.and(orgMng.nvStXNaverClientId.eq(searchDTO.getSchNvStXNaverClientId()));

        if (!CmmnUtil.isEmpty(searchDTO.getSchNvStXNaverClientSecret()))
            builder.and(orgMng.nvStXNaverClientSecret.eq(searchDTO.getSchNvStXNaverClientSecret()));


        return builder;
    }
}
