package handlers

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

	"git.warky.dev/wdevs/whatshooked/pkg/config"
	"git.warky.dev/wdevs/whatshooked/pkg/logging"
)

// Hooks returns the list of all configured hooks
func (h *Handlers) Hooks(w http.ResponseWriter, r *http.Request) {
	hooks := h.hookMgr.ListHooks()
	w.Header().Set("Content-Type", "application/json")
	writeJSON(w, hooks)
}

// AddHook adds a new hook to the system
func (h *Handlers) AddHook(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var hook config.Hook
	if err := json.NewDecoder(r.Body).Decode(&hook); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	h.hookMgr.AddHook(hook)

	// Update config
	h.config.Hooks = h.hookMgr.ListHooks()
	if h.configPath != "" {
		if err := config.Save(h.configPath, h.config); err != nil {
			logging.Error("Failed to save config after adding hook", "hook_id", hook.ID, "error", err)
		} else {
			logging.Info("Config saved after adding hook", "hook_id", hook.ID)
		}
	}

	w.WriteHeader(http.StatusCreated)
	writeJSON(w, map[string]string{"status": "ok", "hook_id": hook.ID})
}

// RemoveHook removes a hook from the system
func (h *Handlers) RemoveHook(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req struct {
		ID string `json:"id"`
	}
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if err := h.hookMgr.RemoveHook(req.ID); err != nil {
		http.Error(w, err.Error(), http.StatusNotFound)
		return
	}

	// Update config
	h.config.Hooks = h.hookMgr.ListHooks()
	if h.configPath != "" {
		if err := config.Save(h.configPath, h.config); err != nil {
			logging.Error("Failed to save config after removing hook", "hook_id", req.ID, "error", err)
		} else {
			logging.Info("Config saved after removing hook", "hook_id", req.ID)
		}
	}

	writeJSON(w, map[string]string{"status": "ok"})
}
