package handler

import (
	stdjson "encoding/json"
	"net/http"

	"github.com/saveinmed/backend-go/internal/http/middleware"
	"github.com/saveinmed/backend-go/internal/infrastructure/notifications"
)

// RegisterPushToken registers a device token for push notifications
func (h *Handler) RegisterPushToken(w http.ResponseWriter, r *http.Request) {
	claims, ok := middleware.GetClaims(r.Context())
	if !ok {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	userID := claims.UserID

	var req struct {
		Token    string `json:"token"`
		Platform string `json:"platform"` // "web", "android", "ios"
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if req.Token == "" {
		http.Error(w, "token is required", http.StatusBadRequest)
		return
	}

	// Get FCM service from handler's notification service
	if fcm, ok := h.svc.GetNotificationService().(*notifications.FCMService); ok {
		if err := fcm.RegisterToken(r.Context(), userID, req.Token); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	stdjson.NewEncoder(w).Encode(map[string]string{
		"status":  "ok",
		"message": "Token registered successfully",
	})
}

// UnregisterPushToken removes a device token
func (h *Handler) UnregisterPushToken(w http.ResponseWriter, r *http.Request) {
	claims, ok := middleware.GetClaims(r.Context())
	if !ok {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	userID := claims.UserID

	var req struct {
		Token string `json:"token"`
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if fcm, ok := h.svc.GetNotificationService().(*notifications.FCMService); ok {
		if err := fcm.UnregisterToken(r.Context(), userID, req.Token); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.WriteHeader(http.StatusNoContent)
}

// TestPushNotification sends a test push notification (for debugging)
func (h *Handler) TestPushNotification(w http.ResponseWriter, r *http.Request) {
	claims, ok := middleware.GetClaims(r.Context())
	if !ok {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	userID := claims.UserID

	if fcm, ok := h.svc.GetNotificationService().(*notifications.FCMService); ok {
		if err := fcm.SendPush(r.Context(), userID,
			"🔔 Teste de Notificação",
			"Esta é uma notificação de teste do SaveInMed!",
			map[string]string{"type": "test"},
		); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

	w.Header().Set("Content-Type", "application/json")
	stdjson.NewEncoder(w).Encode(map[string]string{"status": "sent"})
}
