package com.its.op.dao.repository.its.vms;

import com.its.op.entity.its.vms.TbVmsDsplPrst;
import com.its.op.entity.its.vms.TbVmsDsplPrstKey;
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.util.List;

@Repository
public interface TbVmsDsplPrstRepository extends JpaRepository<TbVmsDsplPrst, TbVmsDsplPrstKey>, JpaSpecificationExecutor<TbVmsDsplPrst> {

    @Query("select p from TbVmsDsplPrst p inner join fetch p.vms vms inner join fetch vms.type tp left outer join fetch vms.state state " +
           " where vms.delYn = 'N' " +
           "   and (p.vmsCtlrNmbr, p.dsplDt) in (select s.vmsCtlrNmbr, max(s.dsplDt) from TbVmsDsplPrst s group by s.vmsCtlrNmbr)")
    List<TbVmsDsplPrst> findAll();

    @Query("select p from TbVmsDsplPrst p inner join fetch p.vms vms inner join fetch vms.type tp left outer join fetch vms.state state  " +
            " where vms.delYn = 'N' " +
            "   and p.vmsCtlrNmbr in :vmsCtlrNmbr " +
            "   and (p.vmsCtlrNmbr, p.dsplDt) in (select s.vmsCtlrNmbr, max(s.dsplDt) from TbVmsDsplPrst s group by s.vmsCtlrNmbr)")
    List<TbVmsDsplPrst> findAllByIds(@Param("vmsCtlrNmbr") List<Long> vmsCtlrNmbr);

    @Query("select p from TbVmsDsplPrst p inner join fetch p.vms vms inner join fetch vms.type tp left outer join fetch vms.state state  " +
            " where vms.delYn = 'N' " +
            "   and p.vmsCtlrNmbr = :vmsCtlrNmbr " +
            "   and p.phase = :phase")
    List<TbVmsDsplPrst> findAllByIdAndPhase(@Param("vmsCtlrNmbr") Long vmsCtlrNmbr, @Param("phase") Integer phase);
}
