package com.example.cattletends.repository;

import com.example.cattletends.entity.ProvinceDailyPrice;
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.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * 省份每日均价Repository
 */
@Repository
public interface ProvinceDailyPriceRepository extends JpaRepository<ProvinceDailyPrice, Integer> {
    
    /**
     * 根据省份和日期查询（用于检查是否已存在，避免重复）
     */
    Optional<ProvinceDailyPrice> findByProvinceAndPriceDate(String province, LocalDate priceDate);
    
    /**
     * 检查省份和日期是否存在
     */
    boolean existsByProvinceAndPriceDate(String province, LocalDate priceDate);
    
    /**
     * 根据省份查询所有记录，按日期降序排序
     */
    List<ProvinceDailyPrice> findByProvinceOrderByPriceDateDesc(String province);
    
    /**
     * 查询所有记录，按日期降序排序
     */
    List<ProvinceDailyPrice> findAllByOrderByPriceDateDesc();
    
    /**
     * 根据省份和日期范围查询
     */
    @Query("SELECT p FROM ProvinceDailyPrice p WHERE p.province = :province AND p.priceDate BETWEEN :startDate AND :endDate ORDER BY p.priceDate DESC")
    List<ProvinceDailyPrice> findByProvinceAndDateRange(
            @Param("province") String province,
            @Param("startDate") LocalDate startDate,
            @Param("endDate") LocalDate endDate
    );
    
    /**
     * 根据日期查询所有省份的每日均价记录，按省份名称升序排序
     */
    List<ProvinceDailyPrice> findByPriceDateOrderByProvinceAsc(LocalDate priceDate);
}

