package opsapi

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

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/pingcap/log"
	"github.com/tidbcloud/observability/pkg/common/constants"
	"github.com/tidbcloud/observability/pkg/common/structs"
	"go.uber.org/zap"
)

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

	// 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")
}

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