package cokr.xit.ens.batch.sched;

import cokr.xit.ens.core.aop.EnsResponseVO;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.modules.ktsigntalk.gibis.service.KtGibisHisService;
import cokr.xit.ens.modules.ktsigntalk.gibis.service.KtGibisService;
import com.querydsl.core.Tuple;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

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

@Slf4j
@Component
@Profile("!local & !local-maria & !local-oracle & !local-test")
@RequiredArgsConstructor
public class EnsKtGibisScheduler {

    private final KtGibisService ktGibisService;
    private final KtGibisHisService ktGibisHisService;
    private final JPAQueryFactory query;


    /**
     * KT 인증톡(지비스) 전송 처리
     * -. "제작성공(makeok)" 상태의 모든 자료에 대해 전송을 수행 한다.
     */
    @Scheduled(cron = "0 */1 9-18 * * *")
    public void sended() {
        EnsResponseVO responseVO = ktGibisService.sendBulkAll();
        log.info("=======================================================");
        log.info("[ENS] KT 인증톡(지비스) 전송처리");
        log.info("결과: {}", responseVO.toString());
        log.info("=======================================================");
    }


    /**
     * KT 인증톡(지비스) 인증토큰 갱신
     */
    @Scheduled(cron = "0 0 0 1 */4 *")
    public void refreshAuthToken() {
        List<Tuple> list = query.select(orgMng.orgCd, orgMng.ktStClientId, orgMng.ktStClientSecret)
                .from(orgMng)
                .where(orgMng.ktStAccessToken.isNotNull())
                .fetch();

        int cntRefresh = list.stream()
                .map(tuple -> {
                    EnsResponseVO<Long> ensResponseVO = ktGibisService.refreshAuthToken(tuple.get(orgMng.orgCd), tuple.get(orgMng.ktStClientId), tuple.get(orgMng.ktStClientSecret));
                    return EnsErrCd.OK.equals(ensResponseVO.getErrCode()) ? 1 : 0;
                })
                .reduce(Integer::sum)
                .orElse(0);

        log.info("=======================================================");
        log.info("[ENS] KT 인증톡(지비스) accessToken 갱신");
        log.info("결과: {} 건 갱신({}/{})", cntRefresh, cntRefresh, list.size());
        log.info("=======================================================");
    }


//    /**
//     * KT 인증톡(지비스) 상태갱신요청이력 영구 삭제
//     */
//    @Scheduled(cron = "4 4 4 * * *")
//    public void deleteStateHis() {
//        EnsResponseVO<Long> ensResponseVO = ktGibisHisService.truncateStatHist();
//        log.info("=======================================================");
//        log.info("[ENS] KT 인증톡(지비스) 상태변경요청이력 영구 삭제");
//        log.info("결과: {} 건 삭제", ensResponseVO.getResultInfo());
//        log.info("=======================================================");
//    }


}
