package api_server

import (
	"os"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/rs/zerolog/log"
	"github.com/spf13/cobra"
	"gitlab.com/tensorsecurity-rd/waf-console/api"
	"gitlab.com/tensorsecurity-rd/waf-console/cmd/api-server/config"

	// "gitlab.com/tensorsecurity-rd/waf-console/cmd/config"

	"gitlab.com/tensorsecurity-rd/waf-console/internal/service"
	es "gitlab.com/tensorsecurity-rd/waf-console/internal/store"
)

func NewApiServer() *gin.Engine {
	router := gin.Default()
	return router
}

func NewRootCommand() *cobra.Command {
	return &cobra.Command{
		Use:   "api-server",
		Short: "Start api-server service.",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			config := config.LoadConfig()
			debugMode := os.Getenv("DEBUG_MODE")
			log.Info().Msgf("DEBUG_MODE: %s", debugMode)
			if debugMode == "true" {
				config.Debug = true
				// config.Conf.Debug = true
			}
			esClient, err := es.CreateEsClientFromConfig(config.ElasticsearchConfig)
			if err != nil {
				panic(err)
			}

			e := api.SetApiRouters(config, config.SSOUrl, esClient)
			esStore := es.NewESStore(es.Config{
				ESBatchSize:   100,
				ESConcurrency: 10,
				ESTimeout:     10 * time.Second,
			}, esClient)
			esStore.Init()
			logConsumerService := service.NewLogConsumerService(nil, esStore, config.KafkaConfig, config.RegionConfig.RegionName)
			go logConsumerService.Consume()
			return e.Run(":8080")
		},
	}
}
