package healthimp

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/tech/sendico/pkg/api/routers/health"
	"github.com/tech/sendico/pkg/mlogger"
	"go.uber.org/zap"
)

type Router struct {
	logger mlogger.Logger
	status *Status
}

func (hr *Router) SetStatus(status health.ServiceStatus) {
	hr.status.setStatus(status)
	hr.logger.Info("New status set", zap.String("status", string(status)))
}

func (hr *Router) Finish() {
	hr.status.Finish()
	hr.logger.Debug("Stopped")
}

func (hr *Router) handle(w http.ResponseWriter, r *http.Request) {
	hr.status.healthHandler()(w, r)
}

func NewRouter(logger mlogger.Logger, router chi.Router, endpoint string) *Router {
	hr := Router{
		logger: logger.Named("health_check"),
	}
	hr.status = StatusHandler(hr.logger)

	logger.Debug("Installing healthcheck middleware...")
	router.Group(func(r chi.Router) {
		ep := endpoint + "/health"
		r.Get(ep, hr.handle)
		logger.Info("Health handler installed", zap.String("endpoint", ep))
	})

	return &hr
}
