package cache

import (
	"sync"
	"time"
)

type DashboardSnapshot struct {
	UploadRate   int64 `json:"upload_rate"`
	DownloadRate int64 `json:"download_rate"`
	Connections  int   `json:"connections"`
	TotalNodes   int   `json:"total_nodes"`
	AliveNodes   int   `json:"alive_nodes"`
	UpdatedAt    time.Time `json:"updated_at"`
}

type Cache struct {
	mu           sync.RWMutex
	lastYAML     []byte
	dashboard    DashboardSnapshot
	proxyLatency map[string]int
}

func New() *Cache {
	return &Cache{
		proxyLatency: make(map[string]int),
	}
}

func (c *Cache) SetLastYAML(yaml []byte) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.lastYAML = append([]byte(nil), yaml...)
}

func (c *Cache) GetLastYAML() []byte {
	c.mu.RLock()
	defer c.mu.RUnlock()
	if c.lastYAML == nil {
		return nil
	}
	return append([]byte(nil), c.lastYAML...)
}

func (c *Cache) SetDashboard(s DashboardSnapshot) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.dashboard = s
}

func (c *Cache) GetDashboard() DashboardSnapshot {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.dashboard
}

func (c *Cache) SetProxyLatency(name string, ms int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.proxyLatency[name] = ms
}

func (c *Cache) GetProxyLatency(name string) (int, bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	v, ok := c.proxyLatency[name]
	return v, ok
}
