package api

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

	"crypto-miner-server/internal/db"
)

// ConfigHandler handles GET/PUT for server configuration settings
type ConfigHandler struct {
	db     *db.Database
	config ConfigProvider
}

// ConfigProvider is an interface for the server config so we don't import main package
type ConfigProvider interface {
	GetConfigJSON() json.RawMessage
	UpdateConfigFromJSON(data json.RawMessage) error
}

func NewConfigHandler(database *db.Database, cp ConfigProvider) *ConfigHandler {
	return &ConfigHandler{
		db:     database,
		config: cp,
	}
}

func (h *ConfigHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case http.MethodGet:
		h.getConfig(w, r)
	case http.MethodPut:
		h.updateConfig(w, r)
	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}

// GET /api/v1/config
func (h *ConfigHandler) getConfig(w http.ResponseWriter, r *http.Request) {
	configJSON := h.config.GetConfigJSON()
	w.Header().Set("Content-Type", "application/json")
	w.Write(configJSON)
}

// PUT /api/v1/config
func (h *ConfigHandler) updateConfig(w http.ResponseWriter, r *http.Request) {
	var body json.RawMessage
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		http.Error(w, `{"error":"Invalid JSON"}`, http.StatusBadRequest)
		return
	}

	if err := h.config.UpdateConfigFromJSON(body); err != nil {
		http.Error(w, `{"error":"`+err.Error()+`"}`, http.StatusInternalServerError)
		return
	}

	// Return updated config
	h.getConfig(w, r)
}
