package security

import (
	"sync"
	"time"

	"github.com/fonchain/utils/security"
	"go.uber.org/zap"
)

var (
	ImageScanner *security.ImageScanner
	globalConfig *security.Config
	configMutex  sync.RWMutex
)

func Init() {
	config, err := security.LoadConfigFromFile("../conf/alibabacloud.env")
	if err != nil {
		zap.L().Error("load config fail", zap.Error(err))
		panic(err)
		//err = errors.New("加载黄反配置失败")
		//return false, err
	}
	if err = config.GetSTSToken(); err != nil {
		zap.L().Error("load sts token failed", zap.Error(err))
		panic(err)

	}
	ImageScanner, err = security.NewImageScanner(config)
	if err != nil {
		panic(err)
	}
}

// GetGlobalConfig 获取全局配置实例（单例模式）
func GetGlobalConfig(configFile string) (*security.Config, error) {
	configMutex.RLock()
	if globalConfig != nil {
		// 检查 token 是否还有效
		if !globalConfig.TokenExpiration.IsZero() &&
			time.Now().Before(globalConfig.TokenExpiration.Add(-5*time.Minute)) {
			configMutex.RUnlock()
			return globalConfig, nil
		}
	}
	configMutex.RUnlock()

	// 需要重新加载或刷新
	configMutex.Lock()
	defer configMutex.Unlock()

	// 双重检查
	if globalConfig != nil &&
		!globalConfig.TokenExpiration.IsZero() &&
		time.Now().Before(globalConfig.TokenExpiration.Add(-5*time.Minute)) {
		return globalConfig, nil
	}

	// 加载配置
	config, err := security.LoadConfigFromFile(configFile)
	if err != nil {
		return nil, err
	}

	globalConfig = config
	return globalConfig, nil
}
