package services

import (
	"log"
	"sync"

	"github.com/tapper/backend/database"
	"github.com/tapper/backend/models"
)

var (
	configCache map[string]string
	configMu    sync.RWMutex
)

func LoadPlatformConfig() {
	var configs []models.PlatformConfig
	if err := database.DB.Find(&configs).Error; err != nil {
		log.Printf("[config] Failed to load platform config: %v", err)
		return
	}

	configMu.Lock()
	defer configMu.Unlock()
	configCache = make(map[string]string)
	for _, c := range configs {
		configCache[c.Key] = c.Value
	}
	log.Printf("[config] Loaded %d platform config entries", len(configs))
}

func GetPlatformConfig(key, fallback string) string {
	configMu.RLock()
	defer configMu.RUnlock()
	if val, ok := configCache[key]; ok {
		return val
	}
	return fallback
}

func SetPlatformConfig(key, value string, encrypted bool) error {
	cfg := models.PlatformConfig{
		Key:       key,
		Value:     value,
		Encrypted: encrypted,
	}

	result := database.DB.Where("key = ?", key).First(&models.PlatformConfig{})
	if result.Error != nil {
		if err := database.DB.Create(&cfg).Error; err != nil {
			return err
		}
	} else {
		if err := database.DB.Model(&models.PlatformConfig{}).
			Where("key = ?", key).
			Updates(map[string]interface{}{
				"value":     value,
				"encrypted": encrypted,
			}).Error; err != nil {
			return err
		}
	}

	configMu.Lock()
	defer configMu.Unlock()
	if configCache == nil {
		configCache = make(map[string]string)
	}
	configCache[key] = value
	return nil
}

func GetAllPlatformConfig() ([]models.PlatformConfig, error) {
	var configs []models.PlatformConfig
	err := database.DB.Find(&configs).Error
	return configs, err
}
