package api

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

	"github.com/sdp/control-plane/internal/store"
	"github.com/sdp/protocol"
)

// handlePushRoutes rewrites the gateway's config.php by sending a
// push_routes RPC to the gateway agent. The body lists the routes that
// should be in effect for the given sandbox; rows with targetOcp=true
// are restored from the snapshot the agent keeps.
type pushRoutesReq struct {
	SandboxID string                 `json:"sandboxId"`
	Routes    []store.Route          `json:"routes"`
}

func (s *Server) handlePushRoutes(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "POST only", http.StatusMethodNotAllowed)
		return
	}
	var body pushRoutesReq
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		http.Error(w, "bad json", http.StatusBadRequest)
		return
	}
	if body.SandboxID == "" {
		writeErr(w, http.StatusBadRequest, "sandboxId required")
		return
	}
	if _, err := s.st.GetSandbox(body.SandboxID); err == store.ErrNotFound {
		http.Error(w, "sandbox not found", http.StatusNotFound)
		return
	} else if err != nil {
		writeErr(w, http.StatusInternalServerError, err.Error())
		return
	}
	if err := s.st.SetRoutes(body.SandboxID, body.Routes); err != nil {
		writeErr(w, http.StatusInternalServerError, err.Error())
		return
	}
	overrides := make([]protocol.RouteOverride, 0, len(body.Routes))
	for _, r := range body.Routes {
		overrides = append(overrides, protocol.RouteOverride{
			Key:       r.Key,
			Value:     r.Value,
			TargetOCP: r.TargetOCP,
		})
	}
	if err := s.callAgentPushRoutes(context.Background(), body.SandboxID, overrides); err != nil {
		writeErr(w, http.StatusBadGateway, err.Error())
		return
	}
	writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
