package app

import (
	"encoding/base64"
	"fmt"
	"os"

	"github.com/spf13/cobra"
	"gitlab.com/security-rd/go-pkg/logging"
	"gitlab.com/tensorsecurity-rd/waf-console/api"
	"gitlab.com/tensorsecurity-rd/waf-console/pkg/generated/clientset/versioned"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"k8s.io/client-go/rest"
)

func NewRootCommand() *cobra.Command {
	return &cobra.Command{
		Use:   "waf-console",
		Short: "Start waf-console service.",
		Args:  cobra.ExactArgs(0),
		RunE: func(cmd *cobra.Command, args []string) error {
			config := LoadConfig()
			debugMode := os.Getenv("DEBUG_MODE")
			logging.Get().Info().Msgf("DEBUG_MODE: %s", debugMode)
			if debugMode == "true" {
				config.Debug = true
				// config.Conf.Debug = true
			}
			dbConfig := config.DBConfig
			var db *gorm.DB
			var err error
			if dbConfig != nil {
				dns := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Database)
				db, err = gorm.Open(mysql.Open(dns), &gorm.Config{})
				if err != nil {
					panic(err)
				}
			} else {
				panic("dbConfig is nil")
			}

			caData, err := base64.StdEncoding.DecodeString(config.RegionConfigs[0].CAData)
			if err != nil {
				panic(err)
			}
			clientCertData, err := base64.StdEncoding.DecodeString(config.RegionConfigs[0].ClientCertData)
			if err != nil {
				panic(err)
			}
			clientKeyData, err := base64.StdEncoding.DecodeString(config.RegionConfigs[0].ClientKeyData)
			if err != nil {
				panic(err)
			}
			client := versioned.NewForConfigOrDie(&rest.Config{
				Host: config.RegionConfigs[0].ApiServer,
				TLSClientConfig: rest.TLSClientConfig{
					Insecure: false,
					CAData:   caData,
					CertData: clientCertData,
					KeyData:  clientKeyData,
				},
				// BearerToken: "1234567890",
			})

			e := api.SetRouters(db, client)
			return e.Run(":8080")
		},
	}
}
