package dev.lions.unionflow.server.resource;

import io.quarkus.security.Authenticated;
import io.quarkus.websockets.next.OnClose;
import io.quarkus.websockets.next.OnOpen;
import io.quarkus.websockets.next.OnTextMessage;
import io.quarkus.websockets.next.WebSocket;
import io.quarkus.websockets.next.WebSocketConnection;
import org.jboss.logging.Logger;

/**
 * Endpoint WebSocket pour le dashboard temps réel.
 * Les clients mobiles et web se connectent ici pour recevoir les mises à jour.
 * Types de messages supportés : stats_update, new_activity, event_update, notification, pong
 */
@Authenticated
@WebSocket(path = "/ws/dashboard")
public class DashboardWebSocketEndpoint {

    private static final Logger LOG = Logger.getLogger(DashboardWebSocketEndpoint.class);

    @OnOpen
    public String onOpen(WebSocketConnection connection) {
        LOG.infof("WebSocket connection opened: %s", connection.id());
        return "{\"type\":\"connected\",\"data\":{\"message\":\"Connected to UnionFlow Dashboard WebSocket\"}}";
    }

    @OnTextMessage
    public String onMessage(String message, WebSocketConnection connection) {
        LOG.debugf("WebSocket message received from %s: %s", connection.id(), message);

        if (message == null) {
            return "{\"type\":\"ack\",\"data\":{\"received\":true}}";
        }

        // Répondre aux pings avec un pong (heartbeat)
        if ("ping".equalsIgnoreCase(message.trim()) || message.contains("\"type\":\"ping\"")) {
            return "{\"type\":\"pong\",\"data\":{\"timestamp\":" + System.currentTimeMillis() + "}}";
        }

        // Accusé de réception pour les autres messages
        return "{\"type\":\"ack\",\"data\":{\"received\":true}}";
    }

    @OnClose
    public void onClose(WebSocketConnection connection) {
        LOG.infof("WebSocket connection closed: %s", connection.id());
    }
}
