package api

import (
	"encoding/json"
	"git.makki.io/makki/libgo/cmn"
	"git.makki.io/makki/libgo/dbu"
	"git.makki.io/makki/libgo/mhttp"
	"github.com/go-chi/chi/v5"
	"net/http"
)

func tmplPost(w http.ResponseWriter, r *http.Request) {
	companyID := cmn.StrToInt64(chi.URLParam(r, "companyID"))
	var body json.RawMessage

	err := cmn.BodyToJsonReq(r, &body)
	if err != nil {
		mhttp.InternalServerError(w, err)
		return
	}

	sq := "update cm set tmpl = $2 where id = $1"
	_, err = dbu.DB.Exec(r.Context(), sq, companyID, body)
	if err != nil {
		mhttp.InternalServerError(w, err)
		return
	}

	mhttp.ResponseSuccess(w, true)
}

func tmplGet(w http.ResponseWriter, r *http.Request) {
	companyID := cmn.StrToInt64(chi.URLParam(r, "companyID"))
	var body json.RawMessage

	sq := "select tmpl from cm where id = $1"
	err := dbu.DB.QueryRow(r.Context(), sq, companyID).Scan(&body)
	if err != nil {
		mhttp.InternalServerError(w, err)
		return
	}

	mhttp.ResponseSuccess(w, body)
}
