package kr.lunaticbum.back.lun.repository

import kr.lunaticbum.back.lun.model.WebBookmark
import org.springframework.data.domain.Pageable
import org.springframework.data.mongodb.repository.Aggregation
import org.springframework.data.mongodb.repository.Query
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono

@Repository
interface WebBookmarkRepository : ReactiveMongoRepository<WebBookmark, String> {

    // [검색용] 키워드가 제목, 코멘트, 태그, 설명 중 포함 + 공개된 북마크 + 커서 적용
    @Query("{ " +
            "  '\$and': [ " +
            "    { 'visibility': { '\$in': ?0 }, 'savedAt': { '\$lt': ?2 } }, " +
            "    { '\$or': [ " +
            "      { 'title': { '\$regex': ?1, '\$options': 'i' } }, " +
            "      { 'userComment': { '\$regex': ?1, '\$options': 'i' } }, " +
            "      { 'tags': { '\$regex': ?1, '\$options': 'i' } }, " +
            "      { 'description': { '\$regex': ?1, '\$options': 'i' } } " +
            "    ] } " +
            "  ] " +
            "}")
    fun searchBookmarks(visibilities: List<String>, keyword: String, maxTime: Long, pageable: Pageable): Flux<WebBookmark>
    // WebBookmarkRepository 인터페이스 내부에 추가
// savedAt이 특정 시간(?1)보다 작은 것들 중 최신순 조회
    fun findByVisibilityInAndSavedAtLessThanOrderBySavedAtDesc(
        visibilities: List<String>,
        maxTime: Long,
        pageable: Pageable
    ): Flux<WebBookmark>


    fun findByUserIdOrderBySavedAtDesc(userId: String): Flux<WebBookmark>
    fun findByVisibilityInOrderBySavedAtDesc(visibilities: List<String>, pageable: Pageable): Flux<WebBookmark>
    fun countByVisibilityIn(visibilities: List<String>): Mono<Long>

    fun findByMetadataStatus(status: String): Flux<WebBookmark>

    // [추가] 필터링을 위한 고유 카테고리 및 태그 목록 조회 (이 위치로 이동)
    @Aggregation("{ \$unwind: '\$tags' }", "{ \$group: { _id: '\$tags' } }")
    fun findDistinctTags(): Flux<Map<String, Any>>

    @Aggregation("{ \$group: { _id: '\$category' } }")
    fun findDistinctCategories(): Flux<Map<String, Any>>
}

