package handler

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

	"github.com/flowy-live/llink/internal/utils/flog"

	"github.com/flowy-live/llink/internal/human/pushnotify"
	"github.com/flowy-live/llink/internal/middleware"
)

type RegisterPushTokenRequest struct {
	Token      string `json:"token"`
	Platform   string `json:"platform"`
	AppVersion string `json:"app_version"`
}

type UnregisterPushTokenRequest struct {
	Token string `json:"token"`
}

// RegisterPushToken upserts an Expo token; ON CONFLICT transparently re-binds
// a token to a new human after a device-level account switch.
func (h *Handler) RegisterPushToken(w http.ResponseWriter, r *http.Request) {
	humanId, ok := middleware.HumanIdFromContext(r.Context())
	if !ok {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	var req RegisterPushTokenRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "invalid request body", http.StatusBadRequest)
		return
	}

	err := h.pushTokenSvc.Register(r.Context(), humanId, pushnotify.RegisterInput{
		Token:      req.Token,
		Platform:   pushnotify.Platform(req.Platform),
		AppVersion: req.AppVersion,
	})
	if err != nil {
		if errors.Is(err, pushnotify.ErrInvalidPlatform) || errors.Is(err, pushnotify.ErrInvalidToken) {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		flog.Error("failed to register push token", "error", err, "humanId", humanId)
		http.Error(w, "internal server error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}

// UnregisterPushToken returns 204 whether or not the token existed (idempotent).
func (h *Handler) UnregisterPushToken(w http.ResponseWriter, r *http.Request) {
	humanId, ok := middleware.HumanIdFromContext(r.Context())
	if !ok {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	var req UnregisterPushTokenRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "invalid request body", http.StatusBadRequest)
		return
	}

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

	err := h.pushTokenSvc.Unregister(r.Context(), humanId, req.Token)
	if err != nil && !errors.Is(err, pushnotify.ErrNotFound) {
		flog.Error("failed to unregister push token", "error", err, "humanId", humanId)
		http.Error(w, "internal server error", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
