package notificationimp

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

	"github.com/tech/sendico/notification/internal/server/notificationimp/telegram"
	"go.uber.org/zap"
)

const telegramWebhookMaxBody = 1 << 20

func (a *NotificationAPI) handleTelegramWebhook(w http.ResponseWriter, r *http.Request) {
	if a == nil || a.confirm == nil {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	var update telegram.Update
	dec := json.NewDecoder(io.LimitReader(r.Body, telegramWebhookMaxBody))
	if err := dec.Decode(&update); err != nil {
		if a.logger != nil {
			a.logger.Warn("Failed to decode telegram webhook update", zap.Error(err))
		}
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	a.confirm.HandleUpdate(r.Context(), &update)
	w.WriteHeader(http.StatusOK)
}
