package csbi

import (
	"context"
	"fmt"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	log "github.com/sirupsen/logrus"
)

var httpServer *http.Server

func stopHttpServer(ctx context.Context) error {
	log.Info("shutting down http server")
	return httpServer.Shutdown(ctx)
}

func registerHttpHandler() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Println("Recovered in f", r)
		}
	}()
	http.HandleFunc("/livez", healthCheck)
	http.HandleFunc("/readyz", readynessCheck)
	http.Handle("/metrics", promhttp.Handler())
}

func startHttpServer() {
	registerHttpHandler()
	httpServer = &http.Server{Addr: ":9338"}
	go func() {
		log.Infof("starting http endpoints. listening to %v", httpServer.Addr)
		if err := httpServer.ListenAndServe(); err != nil {
			log.Error(err)
		}
	}()
}

func healthCheck(writer http.ResponseWriter, request *http.Request) {
	writer.WriteHeader(http.StatusOK)
}

func readynessCheck(writer http.ResponseWriter, request *http.Request) {
	writer.WriteHeader(http.StatusOK)
}
