package com.viettel.campaign.repository.ccms_full;

import com.viettel.campaign.config.DataSourceQualify;
import com.viettel.campaign.model.ccms_full.CampaignCustomer;
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;

@Repository
@Transactional(DataSourceQualify.CCMS_FULL)
public interface CampaignCustomerRepository extends JpaRepository<CampaignCustomer, Long>, CampaignCustomerRepositoryCustom {
    @Query(value = "SELECT COUNT(*) " +
            "FROM CAMPAIGN_CUSTOMER CC JOIN CAMPAIGN_COMPLETE_CODE CCC ON CC.CAMPAIGN_ID = CCC.CAMPAIGN_ID " +
            "WHERE CC.STATUS = 3 AND CC.CAMPAIGN_ID = :campaignId AND CC.CUSTOMER_ID = :customerId AND CCC.IS_RECALL = 1 AND CCC.STATUS = 1 ",
            nativeQuery = true)
    Long getCustomerRecall(@Param("campaignId") Long campaignId, @Param("customerId") Long customerId);

    @Query(value = "SELECT cc.customer_id \n" +
            "FROM campaign_customer cc LEFT JOIN receive_cust_log cl ON cc.customer_id = cl.customer_id\n" +
            "WHERE cc.campaign_id = :campaignId \n" +
            "  AND cc.agent_id = :agentId \n" +
            "  AND cc.in_campaign_status = 1 \n" +
            "  AND cl.customer_id IS NULL \n" +
            "  AND EXISTS(SELECT 1 \n" +
            "        FROM campaign_complete_code ccc \n" +
            "        WHERE cc.status = ccc.complete_value \n" +
            "          AND ccc.status = 1 \n" +
            "          AND ccc.is_recall = 1 \n" +
            "          AND ccc.complete_type = 2 \n" +
            "          AND ccc.company_site_id = :companySiteId) \n" +
            "  AND cc.recall_time <= SYSDATE\n" +
            "  AND cc.recall_time + interval :apParam MINUTE >= SYSDATE", nativeQuery = true)
    List<CampaignCustomer> getCustomerRecallDate(@Param("campaignId") Long campaignId, @Param("agentId") Long agentId, @Param("companySiteId") Long companySiteId, @Param("apParam") String apParam);

    CampaignCustomer findCampaignCustomerByCampaignCustomerId(Long id);
}
