package com.its.api.its.repository.vms;

import com.its.api.its.model.entity.vms.TbVmsDsplPrst;
import com.its.api.its.model.entity.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;
import java.util.Optional;

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

    @Query("select p from TbVmsDsplPrst p inner join p.vms vms " +
           " 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 p.vms vms " +
            " 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 p.vms vms " +
            " where vms.delYn = 'N' " +
            "   and p.vmsCtlrNmbr = :vmsCtlrNmbr " +
            "   and p.phase = :phase")
    List<TbVmsDsplPrst> findAllByIdAndPhase(@Param("vmsCtlrNmbr") Long vmsCtlrNmbr, @Param("phase") Integer phase);
}
