package logs

import (
	"context"
	"time"

	"gitlab.com/uafrica/go-utils/config"
	"gitlab.com/uafrica/go-utils/logger"
	"gitlab.com/uafrica/go-utils/redis"
)

type Config struct {
	ActionsKeep                 bool  `json:"actions_keep" doc:"Set true to keep list of actions in logs"`
	ActionsMaxSQLLength         int64 `json:"actions_max_sql_length" doc:"Set length of SQL query to keep in action list (default 0 = delete)"`
	ActionsMaxSQSReqBodyLength  int64 `json:"actions_max_sqs_req_body_length" doc:"Set length of SQS Request body to keep in action list (default 0 = delete)"`
	ActionsMaxAPIReqBodyLength  int64 `json:"actions_max_api_req_body_length" doc:"Set length of API Request body to keep in action list (default 0 = delete)"`
	ActionsMaxAPIResBodyLength  int64 `json:"actions_max_api_res_body_length" doc:"Set length of API Response body to keep in action list (default 0 = delete)"`
	ActionsMaxSearchQueryLength int64 `json:"actions_max_search_query_length" doc:"Set length of search query to keep in action list (default 0 = delete)"`
}

const configPrefix = "LOGS"

var (
	logConfig         Config
	dynamicLogConfig  Config
	dynamicExpireTime time.Time
	redisCli          redis.IRedis
)

func init() {
	if err := config.LoadEnv(configPrefix, &logConfig); err != nil {
		logger.Errorf("failed to load LOGS config: %+v", err)
	}
	dynamicLogConfig = logConfig
	dynamicExpireTime = time.Now()

	//see if can load overrides from redis
	var err error
	redisCli, err = redis.New(context.Background())
	if err != nil {
		logger.Errorf("Not able to connect to REDIS for runtime %s config: %+v", configPrefix, err)
	}
}

//todo: call only on each use and check expiry time before reading from REDIS again, e.g. reload no faster that 10s
func currentLogConfig() Config {
	if redisCli == nil || dynamicExpireTime.After(time.Now()) {
		return dynamicLogConfig
	}

	//time to attempt reload
	//copy static config then overload values which are defined from REDIS
	dynamicLogConfig = logConfig
	dynamicExpireTime = time.Now().Add(time.Second * 10)

	if err := config.Load(configPrefix, &dynamicLogConfig, redisCli); err != nil {
		logger.Errorf("failed to load %s config from REDIS", configPrefix)
	} else {
		logger.Debugf("Loaded %s config: %+v", configPrefix, dynamicLogConfig)
	}
	return dynamicLogConfig
} //runtimeConfigLoad