package server

import (
	"context"
	"fmt"
	"time"

	"github.com/gin-contrib/pprof"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/tidbcloud/dataflow-service-ng/internal/config"
	"github.com/tidbcloud/dataflow-service-ng/internal/metrics"
	"github.com/tidbcloud/dataflow-service-ng/pkg/log"
)

type MetricsServer struct {
	httpServer *gin.Engine
}

func NewMetricsServer(ctx context.Context) (*MetricsServer, error) {
	prometheus.MustRegister(metrics.NewUptimeCollector(time.Now().Unix()))
	s := &MetricsServer{}
	eng := gin.Default()
	s.httpServer = eng
	eng.Use(AllowAll())
	eng.Any("/metrics", gin.WrapH(promhttp.Handler()))
	eng.Any("/healthz", func(c *gin.Context) {
		c.Status(200)
	})
	pprof.Register(eng)
	return s, nil
}

func (s *MetricsServer) ServerMetrics(ctx context.Context) error {
	if config.Global().ServerConfig.MetricsPort <= 0 {
		log.GetLogger(ctx).Info("metrics server not enabled")
		return nil
	}
	httpAddr := fmt.Sprintf("0.0.0.0:%d", config.Global().ServerConfig.MetricsPort)
	return s.httpServer.Run(httpAddr)
}
