package dataapi

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/metrics"
	"github.com/tidbcloud/observability/pkg/common/structs"
	"go.uber.org/zap"
	controller_metrics "sigs.k8s.io/controller-runtime/pkg/metrics"
)

func StartService(ctx context.Context, serviceInfo structs.ServiceInfo) {

	switch serviceInfo.Env {
	case constants.EnvDev:
		gin.SetMode(gin.DebugMode)
	case constants.EnvStaging:
		gin.SetMode(gin.TestMode)
	case constants.EnvProd:
		gin.SetMode(gin.ReleaseMode)
	}

	g := gin.New()
	g.Use(cors.New(corsConfig()))
	route(g)

	port := serviceInfo.Port
	addr := fmt.Sprintf(":%d", port)

	srv := &http.Server{
		Addr:              addr,
		Handler:           g,
		ReadHeaderTimeout: constants.GinReadHeaderTimeout,
		IdleTimeout:       constants.GinIdleTimeout,
	}

	// initial boot prometheus client
	go prometheusBoot(serviceInfo.MetricsPort)

	// Initializing the server in a goroutine so that
	// it won't block the graceful shutdown handling below
	go func() {
		if serviceInfo.EnableHttps {
			if err := srv.ListenAndServeTLS(serviceInfo.Certificate.CrtFilePath, serviceInfo.Certificate.KeyFilePath); err != nil && errors.Is(err, http.ErrServerClosed) {
				log.Info("listen error", zap.Error(err))
			}
		} else {
			if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
				log.Info("listen error", zap.Error(err))
			}
		}
	}()
	<-ctx.Done()
	timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(timeoutCtx); err != nil {
		log.Fatal("Server forced to shutdown", zap.Error(err))
	}
	log.Info("Wait for all graceful shutdown", zap.Duration("Shutdown_Wait_Time", constants.GracefulShutDownWait))
	t := time.NewTimer(constants.GracefulShutDownWait)
	<-t.C
	log.Info("Server exiting")

}

// prometheusBoot
// @Description: boot prometheus
// @Parameter metricsPort
func prometheusBoot(metricsPort int) {
	// add boot_time metrics
	metrics.GetMetrics().BootTimeGaugeMetric.
		With(prometheus.Labels{metrics.ServiceLabel: constants.ObservabilityRegionalDataServer}).
		SetToCurrentTime()

	mux := http.NewServeMux()
	h := promhttp.HandlerFor(controller_metrics.Registry,
		promhttp.HandlerOpts{})
	mux.Handle("/metrics", h)

	if metricsPort <= 0 {
		metricsPort = constants.DefaultObservabilityRegionalDataServerMetricsPort
	}
	log.Info("prometheus listen address", zap.String("Address", fmt.Sprintf("0.0.0.0:%d", metricsPort)))
	srv := &http.Server{
		Addr:              "0.0.0.0:" + strconv.Itoa(metricsPort),
		Handler:           mux,
		ReadHeaderTimeout: constants.GinReadHeaderTimeout,
	}
	err := srv.ListenAndServe()
	if err != nil {
		log.Fatal("prometheus listen and serve error: " + err.Error())
	}
}

// corsConfig
// @Description: build cors config
// @return cors.Config
func corsConfig() cors.Config {
	config := cors.DefaultConfig()
	config.AllowHeaders = []string{"*"}
	config.AllowCredentials = true
	config.AllowOriginFunc = func(origin string) bool {
		return true
	}
	return config
}
