package kr.lunaticbum.back.lun.service

import kr.lunaticbum.back.lun.model.Comment
import kr.lunaticbum.back.lun.repository.CommentRepository
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import java.net.URLDecoder


@Service
class CommentService(private val commentRepository: CommentRepository) {

    /**
     * [수정] 각 댓글의 content를 URL 디코딩하는 로직을 추가합니다.
     */
    private fun decodeCommentContent(comment: Comment): Comment {
        comment.content = comment.content?.let { URLDecoder.decode(it, "UTF-8") }
        return comment
    }

    fun getRepliesForComment(parentId: String): Flux<Comment> {
        return commentRepository.findByParentIdOrderByWriteTimeAsc(parentId).map { decodeCommentContent(it) } // [수정] 디코딩 로직 추가
    }
    fun addComment(comment: Comment): Mono<Comment> {
        // 예시: 부모 댓글 존재 여부/권한 검증 등 비즈니스 로직 처리
        return commentRepository.save(comment).map { decodeCommentContent(it) } // [수정] 디코딩 로직 추가
    }

    fun getCommentsForPost(postId: String): Flux<Comment> {
        return commentRepository.findByPostIdAndParentIdIsNullOrderByWriteTimeAsc(postId).map { decodeCommentContent(it) } // [수정] 디코딩 로직 추가
    }
    fun findCommentsByWriter(writer: String, pageable: Pageable): Flux<Comment> { // [신규 추가]
        return commentRepository.findByWriterOrderByWriteTimeDesc(writer, pageable).map { decodeCommentContent(it) } // [수정] 디코딩 로직 추가
    }
    // 기타: 대댓글 불러오기, 신고/삭제, 멘션 알림 등 확장 가능
}
