package com.pharmacopoeia.repository;

import com.pharmacopoeia.entity.Drug;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.time.Instant;
import java.util.List;
import java.util.Optional;

public interface DrugRepository extends JpaRepository<Drug, Long> {
    Optional<Drug> findByDrugId(String drugId);

    long countByIsActiveTrue();

    @Query("SELECT COALESCE(MAX(d.updatedAt), NULL) FROM Drug d")
    Instant findMaxUpdatedAt();

    @Query("SELECT d FROM Drug d WHERE d.isActive = true AND d.category NOT IN ('通则', '凡例与纲要', '凡例', '概要')")
    Page<Drug> findByIsActiveTrue(Pageable pageable);

    @Query("SELECT d FROM Drug d WHERE d.isActive = true AND d.category = :category AND d.category NOT IN ('通则', '凡例与纲要', '凡例', '概要')")
    Page<Drug> findByCategoryAndIsActiveTrue(@Param("category") String category, Pageable pageable);

    @Query("SELECT d FROM Drug d WHERE d.isActive = true AND d.category NOT IN ('通则', '凡例与纲要', '凡例', '概要') AND (d.name ILIKE %:keyword% OR d.pinyin ILIKE %:keyword%)")
    Page<Drug> searchByKeyword(@Param("keyword") String keyword, Pageable pageable);

    @Query("SELECT DISTINCT d.category FROM Drug d WHERE d.category IS NOT NULL ORDER BY d.category")
    List<String> findDistinctCategories();

    @Query("SELECT DISTINCT d.category, d.subcategory FROM Drug d WHERE d.category IS NOT NULL ORDER BY d.category, d.subcategory")
    List<Object[]> findCategorySubcategoryPairs();
}
