package com.viettel.campaign.repository.ccms_full;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.TimeRangeDialMode;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author anhvd_itsol
 */

@Repository
@Transactional(DataSourceQualify.CCMS_FULL)
public interface TimeRangeDialModeRepository extends JpaRepository<TimeRangeDialMode, Long> {

    List<TimeRangeDialMode> findTimeRangeDialModeByCampaignIdAndCompanySiteId(Long campaignId, Long companySiteId);

    @Query(value = "SELECT * " +
            "FROM (SELECT Z.* " +
            "      FROM TIME_ZONE_DIAL_MODE Z INNER JOIN CAMPAIGN C ON Z.CAMPAIGN_ID = C.CAMPAIGN_ID " +
            "      WHERE Z.COMPANY_SITE_ID = :companySiteId " +
            "        AND Z.CAMPAIGN_ID = :campaignId " +
            "        AND TO_DATE(START_TIME, 'YYYY/MM/DD') <= TO_DATE(SYSDATE, 'YYYY/MM/DD') " +
            "        AND TO_DATE((to_char(SYSDATE, 'YYYY/MM/DD') || ' ' || Z.HOUR || ':' || Z.MINUTE || ':00'), 'YYYY/MM/DD HH24:MI:SS') <= SYSDATE " +
            "      ORDER BY TO_DATE((to_char(SYSDATE, 'YYYY/MM/DD') || ' ' || Z.HOUR || ':' || Z.MINUTE || ':00'), 'YYYY/MM/DD HH24:MI:SS') DESC " +
            "     ) WHERE ROWNUM = 1", nativeQuery = true)
    TimeRangeDialMode findDialModeAtCurrent(@Param("companySiteId") Long companySiteId, @Param("campaignId") Long campaignId);

    void deleteAllByCampaignIdAndCompanySiteId(Long campaignId, Long companySiteId);
}
