package com.its.api.bis.repository;

import com.its.api.bis.model.entity.BitStatusHistory;
import com.its.api.bis.model.entity.BitStatusHistoryKey;
import com.its.api.its.model.dto.common.SttsHsErrCntInf;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface BitStatusHistoryRepository extends JpaRepository<BitStatusHistory, BitStatusHistoryKey>, JpaSpecificationExecutor<BitStatusHistory> {

    @Query("select p from BitStatusHistory p " +
            " where (p.bitid, p.recorddate, p.recordtimestamp) " +
            "    in (select h.bitid, max(h.recorddate), max(h.recordtimestamp) " +
            "          from BitStatusHistory h " +
            "         where h.recorddate >= :fromDt " +
            "         group by h.bitid) ")
    List<BitStatusHistory> findAllStts(@Param("fromDt") LocalDateTime fromDt);

    @Query("select p from BitStatusHistory p " +
            " where (p.bitid, p.recorddate, p.recordtimestamp) " +
            "    in (select h.bitid, max(h.recorddate), max(h.recordtimestamp) " +
            "          from BitStatusHistory h " +
            "         where h.recorddate >= :fromDt " +
            "         group by h.bitid) " +
            "  and p.wcommstatus <> '1'")
    List<BitStatusHistory> findAllCommError(@Param("fromDt") LocalDateTime fromDt);

    @Query("select p.bitid as nmbr, count(p.bitid) as errCnt " +
            "  from BitStatusHistory p " +
            " where p.recorddate >= :fromDt " +
            "   and p.wcommstatus <> '1' " +
            " group by p.bitid")
    List<SttsHsErrCntInf> findAllCommErrorCount(@Param("fromDt") LocalDateTime fromDt);

}
