package config

import (
	"encoding/json"
	"os"

	"github.com/rs/zerolog/log"
	"gitlab.com/tensorsecurity-rd/waf-console/internal/config"
)

type RegionConfig struct {
	RegionCode string `json:"region_code"`
	RegionName string `json:"region_name"`
	ApiServer  string `json:"api_server"`
}

type Config struct {
	RegionConfig        RegionConfig                `json:"region_config"`
	Debug               bool                        `json:"debug"`
	SSOUrl              string                      `json:"sso_url"`
	ElasticsearchConfig *config.ElasticsearchConfig `json:"elasticsearch_config"`
	KafkaConfig         *config.KafkaConfig         `json:"kafka_config"`
}

// type ElasticsearchConfig struct {
// 	Url      string `json:"url"`
// 	Username string `json:"username"`
// 	Password string `json:"password"`
// 	Sniff    bool   `json:"sniff"`
// }

// type KafkaConfig struct {
// 	Brokers    []string `json:"brokers"`
// 	Topic      string   `json:"topic"`
// 	Group      string   `json:"group"`
// 	AuthMethod string   `json:"auth_method"`
// 	Username   string   `json:"username"`
// 	Password   string   `json:"password"`
// 	ScramAlgo  string   `json:"scram_algo"`
// }

func LoadConfig() *Config {
	configFile := "config/config.json"
	if envFile := os.Getenv("CONFIG_FILE"); envFile != "" {
		configFile = envFile
	}

	data, err := os.ReadFile(configFile)
	if err != nil {
		log.Err(err).Msgf("Failed to read config file: %s", configFile)
		return nil
	}

	var config Config
	if err := json.Unmarshal(data, &config); err != nil {
		log.Err(err).Msg("Failed to parse config file")
		return nil
	}
	esPassword := os.Getenv("ELASTIC_PASSWORD")
	if esPassword != "" {
		config.ElasticsearchConfig.Password = esPassword
	}

	kafkaPassword := os.Getenv("KAFKA_PASSWORD")
	if kafkaPassword != "" {
		config.KafkaConfig.Password = kafkaPassword
	}

	return &config
}
