package db_test

import (
	"testing"

	"github.com/user/nanometrics/server/db"
	"github.com/user/nanometrics/server/models"
)

func newTestDB(t *testing.T) *db.DB {
	t.Helper()
	d, err := db.Open(":memory:")
	if err != nil {
		t.Fatalf("open db: %v", err)
	}
	t.Cleanup(func() { d.Close() })
	return d
}

func TestUpsertAndGetAgents(t *testing.T) {
	d := newTestDB(t)
	m := &models.AgentMetrics{Hostname: "srv-01", IP: "10.0.0.1", Status: "online"}
	if err := d.UpsertAgent(m); err != nil {
		t.Fatalf("upsert: %v", err)
	}
	agents, err := d.GetAgents()
	if err != nil {
		t.Fatalf("get agents: %v", err)
	}
	if len(agents) != 1 {
		t.Fatalf("attendu 1 agent, eu %d", len(agents))
	}
	if agents[0].Hostname != "srv-01" {
		t.Errorf("hostname: attendu srv-01, eu %s", agents[0].Hostname)
	}
}

func TestInsertMetrics(t *testing.T) {
	d := newTestDB(t)
	cpu := 42.5
	m := &models.AgentMetrics{Hostname: "srv-01", IP: "10.0.0.1", Status: "online", CPUPercent: &cpu}
	_ = d.UpsertAgent(m)
	if err := d.InsertMetrics(m); err != nil {
		t.Fatalf("insert metrics: %v", err)
	}
	history, err := d.GetMetricsHistory("srv-01", 0, 9999999999)
	if err != nil {
		t.Fatalf("history: %v", err)
	}
	if len(history) != 1 {
		t.Fatalf("attendu 1 entrée, eu %d", len(history))
	}
}

func TestAgentConfig(t *testing.T) {
	d := newTestDB(t)
	cfg := &models.AgentConfig{
		Metrics: models.MetricsConfig{
			CPU: models.MetricProto{UDP: true, MQTT: false},
		},
	}
	if err := d.UpsertAgentConfig("srv-01", cfg); err != nil {
		t.Fatalf("upsert config: %v", err)
	}
	got, err := d.GetAgentConfig("srv-01")
	if err != nil || got == nil {
		t.Fatalf("get config: %v", err)
	}
	if !got.Metrics.CPU.UDP {
		t.Error("CPU.UDP devrait être true")
	}
}

func TestServerConfig(t *testing.T) {
	d := newTestDB(t)
	cfg := models.DefaultServerConfig()
	cfg.TileMinWidth = 300
	if err := d.SetServerConfig(cfg); err != nil {
		t.Fatalf("set config: %v", err)
	}
	got, err := d.GetServerConfig()
	if err != nil {
		t.Fatalf("get config: %v", err)
	}
	if got.TileMinWidth != 300 {
		t.Errorf("tile_min_width: attendu 300, eu %d", got.TileMinWidth)
	}
}
