package com.android.trisolarisserver.component import com.android.trisolarisserver.controller.GuestDocumentResponse import com.android.trisolarisserver.controller.toResponse import com.android.trisolarisserver.db.repo.GuestDocumentRepo import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import org.springframework.web.servlet.mvc.method.annotation.SseEmitter import java.util.UUID @Component class GuestDocumentEvents( private val guestDocumentRepo: GuestDocumentRepo, private val objectMapper: ObjectMapper ) { private val hub = SseHub("guest-documents") { key -> buildSnapshot(key.propertyId, key.guestId) } fun subscribe(propertyId: UUID, guestId: UUID): SseEmitter { val key = GuestDocKey(propertyId, guestId) return hub.subscribe(key) } fun emit(propertyId: UUID, guestId: UUID) { val key = GuestDocKey(propertyId, guestId) hub.emit(key) } @Scheduled(fixedDelayString = "25000") fun heartbeat() { hub.heartbeat() } private fun buildSnapshot(propertyId: UUID, guestId: UUID): List { return guestDocumentRepo .findByPropertyIdAndGuestIdOrderByUploadedAtDesc(propertyId, guestId) .map { it.toResponse(objectMapper) } } } private data class GuestDocKey( val propertyId: UUID, val guestId: UUID )