package com.bcxin.backend.domain.syncs.repositories;

import com.bcxin.runtime.domain.syncs.entities.DataSyncQueueEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;

public interface DataSyncQueueRepository extends JpaRepository<DataSyncQueueEntity,String> {
    @Query("select d from DataSyncQueueEntity d where d.status=com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Initialize order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getPendingData(Pageable pageable);

    @Query("select d from DataSyncQueueEntity d where d.fileSyncStatus=com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Initialize  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getPendingFiles(Pageable pageable);

    @Query("select d from DataSyncQueueEntity d where d.status=com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.SyncViaFTP  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getPendingFtpData(Pageable pageable);

    @Query("select d from DataSyncQueueEntity d where d.fileSyncStatus=com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.SyncViaFTP  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getPendingFtpFilesData(Pageable pageable);

    @Query("select count(d) from DataSyncQueueEntity d where d.fileSyncStatus=com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Initialize or d.status= com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Initialize ")
    int getPendingCount();

    @Query("select d from DataSyncQueueEntity d where d.retryCount<2 and d.status in (com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Error,com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.ErrorViaFTP)  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getRetryableQueueData(Pageable pageable);

    @Query("select d from DataSyncQueueEntity d where d.retryCount<2 and d.fileSyncStatus in (com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Error,com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.ErrorViaFTP)  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getRetryableQueueFile(Pageable pageable);

    @Query("select d from DataSyncQueueEntity d where d.createdTime<=?1 and d.isArchived=com.bcxin.runtime.domain.enums.BooleanStatus.FALSE and d.status in (com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Done,com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.DoneViaFTP) and d.fileSyncStatus in (com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.Done,com.bcxin.runtime.domain.syncs.enums.SyncProcessStatus.DoneViaFTP)  order by d.createdTime asc ")
    Page<DataSyncQueueEntity> getDoneSyncQueues(Date archivedTime, Pageable pageable);
}
