package notificaciones

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

	"github.com/SherClockHolmes/webpush-go"
)

var suscrip webpush.Subscription

func Suscribirse(w http.ResponseWriter, r *http.Request) {

	err := json.NewDecoder(r.Body).Decode(&suscrip)

	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	fmt.Println("=================================")
	fmt.Println("SUBSCRIPTION RECEIVED")
	fmt.Println("Endpoint:", suscrip.Endpoint)
	fmt.Println("P256dh:", suscrip.Keys.P256dh)
	fmt.Println("Auth:", suscrip.Keys.Auth)
	fmt.Println("=================================")
	w.WriteHeader(http.StatusOK)
}

func EnviarNotif(cuerpo string) {

	mensaje := fmt.Sprintf(`{
		"title": "ListaCompra",
		"body":"%s" 
	}`, cuerpo)

	resp, err := webpush.SendNotification(
		[]byte(mensaje),
		&suscrip,
		&webpush.Options{
			Subscriber:      "https://redalberto.ddns.net/www/",
			VAPIDPrivateKey: "uVRs8ykEPA_dgOArU48Yj86XFkDVfiQ8hGXTl8V4aco",
			VAPIDPublicKey:  "BOYO9Jgb1euBnUd4SdXzXKBg2xXK657U3wgy5UQkVT7bSuR5q_2O_sPxcQrC6ai-IYmP-YwKktYTfneFbdB_io4",
		},
	)

	if err != nil {
		fmt.Println("ERROR sending notification:", err)

		return
	}

	defer resp.Body.Close()

	fmt.Println("Notification sent successfully!")

}
func Notificar(w http.ResponseWriter, r *http.Request) {

	w.WriteHeader(http.StatusOK)
}
