package models

import (
	"errors"
	"fmt"
	"time"
)

func GetAllRemoteNodes() []RemoteNode {
	mu.RLock()
	defer mu.RUnlock()
	result := make([]RemoteNode, len(cfg.Nodes))
	copy(result, cfg.Nodes)
	return result
}

func GetRemoteNode(id string) (RemoteNode, error) {
	mu.RLock()
	defer mu.RUnlock()
	for _, n := range cfg.Nodes {
		if n.ID == id {
			return n, nil
		}
	}
	return RemoteNode{}, errors.New("node not found")
}

func AddRemoteNode(n RemoteNode) (RemoteNode, error) {
	mu.Lock()
	defer mu.Unlock()
	n.ID = fmt.Sprintf("node_%d", time.Now().UnixNano())
	cfg.Nodes = append(cfg.Nodes, n)
	return n, persist()
}

func UpdateRemoteNode(id string, n RemoteNode) (RemoteNode, error) {
	mu.Lock()
	defer mu.Unlock()
	for i, node := range cfg.Nodes {
		if node.ID == id {
			n.ID = id
			cfg.Nodes[i] = n
			return n, persist()
		}
	}
	return RemoteNode{}, errors.New("node not found")
}

func DeleteRemoteNode(id string) error {
	mu.Lock()
	defer mu.Unlock()
	for i, n := range cfg.Nodes {
		if n.ID == id {
			cfg.Nodes = append(cfg.Nodes[:i], cfg.Nodes[i+1:]...)
			return persist()
		}
	}
	return errors.New("node not found")
}
