package internal

import (
	"context"

	"exporter/config"

	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	lj "gopkg.in/natefinch/lumberjack.v2"
)

var (
	client *TClient
	logger *zap.Logger
)

func InitClient(cfg *config.Config) error {
	logWriter := zapcore.AddSync(&lj.Logger{
		Filename:   cfg.LogFile,
		MaxBackups: 3,
		MaxSize:    1, // megabytes
		MaxAge:     7, // days
	})
	logCore := zapcore.NewCore(
		zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
		logWriter,
		zap.DebugLevel,
	)
	logger = zap.New(logCore)

	client = NewClient(cfg)
	return nil
}

func Close() error {
	_ = logger.Sync()
	return nil
}

func wrapE(f func(context.Context) error) func(cmd *cobra.Command, args []string) error {
	return func(cmd *cobra.Command, args []string) error {
		return client.Client.Run(context.Background(), f)
	}
}
