package server

import (
	"encoding/json"

	"github.com/gorilla/websocket"
	"github.com/rs/zerolog/log"
)

const TYPE_SIGNALING = "signaling"

type WebRTCWSHandler struct {
}

func (h *WebRTCWSHandler) Handle(messageObject map[string]any, senderId string, sockets map[string]*websocket.Conn) {
	if _, ok := messageObject["type"]; !ok {
		return
	}

	messageType := messageObject["type"]
	switch messageType {
	case TYPE_SIGNALING:
		target, ok := messageObject["target"].(string)
		if !ok {
			log.Error().Msgf("Invalid target in signaling message")
			return
		}
		message := messageObject["message"]
		h.handleSignaling(target, message, senderId, sockets)
	}
}

func (h *WebRTCWSHandler) handleSignaling(target string, message any, senderId string, sockets map[string]*websocket.Conn) {
	ws, ok := sockets[target]
	if !ok {
		log.Error().Msgf("No connection found for target %s", target)
		return
	}
	byteArray, err := json.Marshal(map[string]any{"sender": senderId, "message": message})
	if err != nil {
		log.Error().Msgf("Error marshaling signaling message: %s", err)
		return
	}
	log.Info().Str("target", target).Str("sender", senderId).Msg("sending signaling message to target")
	err = ws.WriteMessage(websocket.TextMessage, byteArray)
	if err != nil {
		log.Error().Msgf("Error writing signaling message to target: %s", err)
		return
	}
}
