package cokr.xit.ens.modules.ktsigntalk.direct.domain.repository;

import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.ktsigntalk.direct.domain.SendDetailKtSigntalk;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;

import java.util.List;
import java.util.Optional;

import static cokr.xit.ens.modules.common.ctgy.intgrnbill.support.entity.QBill.bill;
import static cokr.xit.ens.modules.common.domain.QSendMast.sendMast;
import static cokr.xit.ens.modules.ktsigntalk.direct.domain.QSendDetailKtSigntalk.sendDetailKtSigntalk;

@RequiredArgsConstructor
public class SendDetailKtSigntalkRepositoryImpl implements SendDetailKtSigntalkRepositoryCustom {
    private final JPAQueryFactory query;

//    @Override
//    public List<SendDetailKtSigntalk> findAllFetchBySendMastIdAndMkBillUseYAndUrlIsNull(Long sendMastId, boolean urlIsNull) {
//        return query.selectFrom(sendDetailKtSigntalk)
//                .innerJoin(sendDetailKtSigntalk.sendMast, sendMast)
//                .fetchJoin()
//                .leftJoin(sendDetailKtSigntalk.kkoBillMast, kkoBillMast)
//                .fetchJoin()
//                .where(sendDetailKtSigntalk.sendMast.sendMastId.eq(sendMastId)
//                        .and(sendDetailKtSigntalk.mkBillUseYn.eq("Y"))
//                        .and(urlIsNull ? sendDetailKtSigntalk.kkoBillMast.url.isNull() : sendDetailKtSigntalk.kkoBillMast.url.isNotNull())
//                )
//                .fetch();
//    }

    @Override
    public List<SendDetailKtSigntalk> findAllFetchBySendMastId(Long sendMastId) {
        return query.selectFrom(sendDetailKtSigntalk)
                .innerJoin(sendDetailKtSigntalk.sendMast, sendMast).fetchJoin()
//                .leftJoin(sendDetailKtSigntalk.kkoBillMast, kkoBillMast).fetchJoin()
                .leftJoin(sendDetailKtSigntalk.bill, bill).fetchJoin()
                .where(sendDetailKtSigntalk.sendMast.sendMastId.eq(sendMastId))
                .fetch();
    }

    @Override
    public Optional<SendDetailKtSigntalk> findFetchByClientSrcKeyAndSrcKey(String clientSrcKey, String srcKey) {
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(sendDetailKtSigntalk.srcKey.eq(srcKey));
        if (!CmmnUtil.isEmpty(clientSrcKey))
            builder.and(sendDetailKtSigntalk.clientSrcKey.eq(clientSrcKey));

        return Optional.ofNullable(query.selectFrom(sendDetailKtSigntalk)
                .innerJoin(sendDetailKtSigntalk.sendMast, sendMast).fetchJoin()
                .where(builder)
                .fetchOne());
    }
}
