package httpapi

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

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/structs"
)

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,
	}

	go func() {
		if serviceInfo.EnableHttps {
			if err := srv.ListenAndServeTLS(serviceInfo.Certificate.CrtFilePath, serviceInfo.Certificate.KeyFilePath); err != nil && errors.Is(err, http.ErrServerClosed) {
				log.Printf("listen: %s\n", err)
			}
		} else {
			if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
				log.Printf("listen: %s\n", 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:", err)
	}
	log.Printf("Wait %s for all graceful shutdown\n", constants.GracefulShutDownWait.String())
	t := time.NewTimer(constants.GracefulShutDownWait)
	<-t.C
	log.Println("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.Infof("prometheus listen address [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
}
