package main

// 7 Days to Die V3.0 SandboxCode endpoints.
//
// V3.0 "Dead Hot Summer" removed ~30 gameplay properties from serverconfig.xml
// and replaced them with a single encoded `SandboxCode` carrying all 150 in-game
// Sandbox Options. These endpoints expose the option schema to the settings UI
// and round-trip values <-> code through the authoritative Go codec
// (pkg/sandbox, cracked from the 3.0 Assembly-CSharp), so there is exactly ONE
// implementation of the encoding (no JS copy to drift).
//
//   GET  /api/7dtd/sandbox/schema   -> { categories, presets, defaultCode }
//   POST /api/7dtd/sandbox/encode   { values:{name:val,...} } -> { code }
//   POST /api/7dtd/sandbox/decode   { code:"A..." }           -> { values:{...} }

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

	"github.com/dbledeez/panel/pkg/sandbox"
)

func (h *httpServer) handleSevenDTDSandboxSchema(w http.ResponseWriter, r *http.Request) {
	writeJSON(w, http.StatusOK, map[string]any{
		"categories":  sandbox.Schema(),
		"presets":     sandbox.Presets,
		"defaultCode": "AAAJABJACJADJARFBNC", // game's Adventurer default
		"version":     sandbox.Active.Version(),
	})
}

func (h *httpServer) handleSevenDTDSandboxEncode(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Values map[string]string `json:"values"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "bad json: " + err.Error()})
		return
	}
	code, err := sandbox.Active.Encode(body.Values)
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"code": code})
}

func (h *httpServer) handleSevenDTDSandboxDecode(w http.ResponseWriter, r *http.Request) {
	var body struct {
		Code string `json:"code"`
	}
	if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": "bad json: " + err.Error()})
		return
	}
	vals, err := sandbox.Active.Decode(body.Code)
	if err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})
		return
	}
	writeJSON(w, http.StatusOK, map[string]any{"values": vals})
}
