package handler

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

	"git.yeij.top/AskaEth/Cyrene/platform-bridge/internal/config"
)

// BlocklistHandler exposes CRUD for blocklist settings.
type BlocklistHandler struct {
	store *config.BlocklistStore
}

func NewBlocklistHandler(store *config.BlocklistStore) *BlocklistHandler {
	return &BlocklistHandler{store: store}
}

func (h *BlocklistHandler) RegisterRoutes(mux *http.ServeMux) {
	mux.HandleFunc("/api/v1/settings/blocklist", h.handleBlocklist)
}

func (h *BlocklistHandler) handleBlocklist(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		writeJSON(w, http.StatusOK, h.store.Get())
	case "POST", "PUT":
		var bs config.BlocklistSettings
		if err := json.NewDecoder(r.Body).Decode(&bs); err != nil {
			writeJSON(w, http.StatusBadRequest, errResp("invalid JSON: "+err.Error()))
			return
		}
		if err := h.store.Set(bs); err != nil {
			writeJSON(w, http.StatusBadRequest, errResp(err.Error()))
			return
		}
		writeJSON(w, http.StatusOK, map[string]interface{}{
			"status": "saved",
			"settings": h.store.Get(),
		})
	default:
		writeJSON(w, http.StatusMethodNotAllowed, errResp("method not allowed"))
	}
}
