/*
Copyright © 2024-2025 Thomas von Dein

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package rest

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

	"codeberg.org/scip/anydb/cfg"
)

// used to return to the api client
type Result struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Code    int    `json:"code"`
}

const apiprefix = `/anydb/v1/`

func Runserver(conf *cfg.Config, args []string) error {
	// setup api server
	mux := http.NewServeMux()

	// just in case someone tries to access the non-api url
	mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
		Home(w)
	})

	mux.HandleFunc("GET "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
		RestList(w, r, conf)
	})

	mux.HandleFunc("POST "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
		RestList(w, r, conf)
	})

	mux.HandleFunc("GET "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
		key := r.PathValue("key")
		RestGet(w, r, key, conf)
	})

	mux.HandleFunc("DELETE "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
		key := r.PathValue("key")
		RestDelete(w, r, key, conf)
	})

	mux.HandleFunc("PUT "+apiprefix, func(w http.ResponseWriter, r *http.Request) {
		RestSet(w, r, conf)
	})

	logger := LogHandler()

	return http.ListenAndServe(conf.Listen, logger(mux))
}

/*
Wrapper to respond with proper json status, message and code,
shall be prepared and called by the handlers directly.
*/
func JsonStatus(resp http.ResponseWriter, code int, msg string) {
	success := code == http.StatusOK

	resp.Header().Set("Content-Type", "application/json")
	resp.WriteHeader(code)

	err := json.NewEncoder(resp).Encode(
		Result{
			Code:    code,
			Message: msg,
			Success: success,
		})

	if err != nil {
		log.Fatal(err)
	}
}
