package com.saas.tenant.repository;

import com.saas.tenant.entity.CallCostRecord;
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 java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Repository
public interface CallCostRecordRepository extends JpaRepository<CallCostRecord, Long> {
    
    Optional<CallCostRecord> findByCallSid(String callSid);
    
    List<CallCostRecord> findByProvider(String provider);
    
    List<CallCostRecord> findByCallStartTimeBetween(LocalDateTime start, LocalDateTime end);
    
    @Query("SELECT SUM(c.cost) FROM CallCostRecord c WHERE c.callStartTime BETWEEN :start AND :end")
    BigDecimal getTotalCostBetween(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
    
    @Query("SELECT c.provider, SUM(c.cost) FROM CallCostRecord c WHERE c.callStartTime BETWEEN :start AND :end GROUP BY c.provider")
    List<Object[]> getCostByProviderBetween(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
    
    @Query("SELECT COUNT(c) FROM CallCostRecord c WHERE c.callStartTime BETWEEN :start AND :end")
    Long getCallCountBetween(@Param("start") LocalDateTime start, @Param("end") LocalDateTime end);
}
