package kr.lunaticbum.back.lun.model

import org.bson.BsonType
import org.bson.codecs.pojo.annotations.BsonId
import org.bson.codecs.pojo.annotations.BsonRepresentation
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.repository.ReactiveMongoRepository
import org.springframework.stereotype.Repository
import org.springframework.stereotype.Service
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono

@Document(collection = "Messages")
data class Message(
    @Id
    @BsonId
    @BsonRepresentation(BsonType.OBJECT_ID)
    var id: String? = null,

    var senderId: String,
    var receiverId: String,
    var title: String,
    var content: String,
    var timestamp: Long = System.currentTimeMillis(),
    var isRead: Boolean = false
)

@Repository
interface MessageRepository : ReactiveMongoRepository<Message, String> {
    fun findByReceiverIdOrderByTimestampDesc(receiverId: String): Flux<Message>
    fun countByReceiverIdAndIsRead(receiverId: String, isRead: Boolean): Mono<Long>

    fun findBySenderIdOrderByTimestampDesc(senderId: String): Flux<Message>
}

@Service
class MessageService(private val messageRepository: MessageRepository) {

    fun getMessagesForUser(userId: String): Flux<Message> {
        return messageRepository.findByReceiverIdOrderByTimestampDesc(userId)
    }

    fun getUnreadMessageCount(userId: String): Mono<Long> {
        return messageRepository.countByReceiverIdAndIsRead(userId, false)
    }

    fun sendMessage(senderId: String, receiverId: String, title: String, content: String): Mono<Message> {
        val message = Message(senderId = senderId, receiverId = receiverId, title = title, content = content)
        return messageRepository.save(message)
    }

    fun markMessageAsRead(messageId: String, userId: String): Mono<Message> {
        return messageRepository.findById(messageId)
            .filter { it.receiverId == userId } // 본인 쪽지만 읽음 처리하도록 보안 강화
            .flatMap { message ->
                if (!message.isRead) {
                    message.isRead = true
                    messageRepository.save(message)
                } else {
                    Mono.just(message)
                }
            }
    }

    // [신규] 사용자가 보낸 쪽지를 가져오는 서비스를 추가합니다.
    fun getSentMessagesByUser(userId: String): Flux<Message> {
        return messageRepository.findBySenderIdOrderByTimestampDesc(userId)
    }
}