package health

import (
	"fmt"
	"net/http"

	"github.com/fiskerinc/cloud-services/pkg/logger"
	"github.com/fiskerinc/cloud-services/pkg/utils/envtool"
)

type HealthCheckServer struct {
}

func (h *HealthCheckServer) Serve(configs []Config) error {
	port := envtool.GetEnv("HEALTHCHECK_PORT", "11011")
	server, err := New()
	if err != nil {
		return err
	}

	for _, config := range configs {
		err = server.Register(config)
		if err != nil {
			return err
		}
	}

	logger.Info().Msgf("Health check listening on http://0.0.0.0:%s", port)
	http.Handle("/readiness", server.ReadinessHandler())
	http.Handle("/liveness", server.LivenessHandler())
	logger.Fatal().Err(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)).Send()

	return nil
}
