package org.raddatz.familienarchiv.notification;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class SseEmitterRegistry {

    private final ConcurrentHashMap<UUID, SseEmitter> emitters = new ConcurrentHashMap<>();

    public SseEmitter register(UUID userId) {
        SseEmitter emitter = new SseEmitter(0L); // 0 = no timeout; EventSource reconnects automatically
        emitters.put(userId, emitter);
        emitter.onCompletion(() -> emitters.remove(userId, emitter));
        emitter.onTimeout(()    -> emitters.remove(userId, emitter));
        emitter.onError(e  ->    emitters.remove(userId, emitter));
        return emitter;
    }

    public void send(UUID userId, Object data) {
        SseEmitter emitter = emitters.get(userId);
        if (emitter == null) return;
        try {
            emitter.send(SseEmitter.event().name("notification").data(data));
        } catch (IOException e) {
            log.debug("SSE send failed for user {} — removing emitter", userId);
            emitters.remove(userId, emitter);
        }
    }
}
