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

import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.modules.ktsigntalk.gibis.domain.SendDetailKtGibis;
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.gibis.domain.QSendDetailKtGibis.sendDetailKtGibis;

@RequiredArgsConstructor
public class SendDetailKtGibisRepositoryImpl implements SendDetailKtGibisRepositoryCustom {
    private final JPAQueryFactory query;

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

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

    @Override
    public Optional<SendDetailKtGibis> findFetchByLinkedUuidAndSrcKey(String linkedUuid, String srcKey) {
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(sendDetailKtGibis.srcKey.eq(srcKey));
        if (!CmmnUtil.isEmpty(linkedUuid))
            builder.and(sendDetailKtGibis.linkedUuid.eq(linkedUuid));

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