package com.walkguide.websocket;

import com.walkguide.dto.response.LocationResponse;
import com.walkguide.dto.response.NotificationResponse;
import com.walkguide.dto.response.SosEventResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

/**
 * Service untuk broadcast pesan real-time via WebSocket (STOMP).
 *
 * Dipakai oleh:
 *  - LocationService    → broadcast GPS ke Guardian
 *  - SosService         → broadcast SOS ke Guardian
 *  - NotificationService→ broadcast notif ke User
 *
 * PATTERN: Observer — Guardian/User subscribe ke topic,
 *           LocationBroadcaster push data saat ada update.
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class LocationBroadcaster {

    private final SimpMessagingTemplate messagingTemplate;

    /**
     * Broadcast lokasi GPS user ke Guardian yang subscribe.
     * Guardian Flutter subscribe ke: /topic/location/{userId}
     *
     * @param userId   ID dari ROLE_USER (bukan guardian)
     * @param location Response lokasi terbaru
     */
    public void broadcastLocation(Long userId, LocationResponse location) {
        String destination = "/topic/location/" + userId;
        messagingTemplate.convertAndSend(destination, location);
        log.debug("[WS] Location broadcast → {} | lat={} lng={}",
                destination, location.getLat(), location.getLng());
    }

    /**
     * Broadcast SOS event ke Guardian secara real-time.
     * Guardian Flutter subscribe ke: /queue/sos/{guardianId}
     *
     * @param guardianId ID dari ROLE_GUARDIAN
     * @param sos        SOS event yang baru di-trigger
     */
    public void broadcastSos(Long guardianId, SosEventResponse sos) {
        String destination = "/queue/sos/" + guardianId;
        messagingTemplate.convertAndSend(destination, sos);
        log.info("[WS] SOS broadcast → {} | userId={} status={}",
                destination, sos.getUserId(), sos.getStatus());
    }

    /**
     * Broadcast notifikasi dari Guardian ke User secara real-time.
     * User Flutter subscribe ke: /queue/notif/{userId}
     *
     * @param userId       ID dari ROLE_USER yang menerima notif
     * @param notification Notifikasi yang baru dikirim Guardian
     */
    public void broadcastNotification(Long userId, NotificationResponse notification) {
        String destination = "/queue/notif/" + userId;
        messagingTemplate.convertAndSend(destination, notification);
        log.debug("[WS] Notification broadcast → {} | type={}",
                destination, notification.getNotifType());
    }
}
