package handlers_test

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

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

func testDB(t *testing.T) *db.DB {
	d, _ := db.Open(":memory:")
	t.Cleanup(func() { d.Close() })
	return d
}

func TestServerConfigGetPut(t *testing.T) {
	d := testDB(t)
	h := handlers.ServerConfigHandler(d)

	r := httptest.NewRequest(http.MethodGet, "/api/config", nil)
	w := httptest.NewRecorder()
	h(w, r)
	if w.Code != 200 {
		t.Fatalf("GET status: %d", w.Code)
	}
	var got models.ServerConfig
	json.NewDecoder(w.Body).Decode(&got)
	if got.TileMinWidth != 220 {
		t.Errorf("tile_min_width défaut: %d", got.TileMinWidth)
	}

	cfg := models.DefaultServerConfig()
	cfg.TileMinWidth = 300
	body, _ := json.Marshal(cfg)
	r2 := httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body))
	w2 := httptest.NewRecorder()
	h(w2, r2)
	if w2.Code != 204 {
		t.Fatalf("PUT status: %d", w2.Code)
	}

	r3 := httptest.NewRequest(http.MethodGet, "/api/config", nil)
	w3 := httptest.NewRecorder()
	h(w3, r3)
	var got2 models.ServerConfig
	json.NewDecoder(w3.Body).Decode(&got2)
	if got2.TileMinWidth != 300 {
		t.Errorf("tile_min_width après PUT: %d", got2.TileMinWidth)
	}
}

func TestAgentsHandler(t *testing.T) {
	d := testDB(t)
	h := handlers.AgentsHandler(d)

	r := httptest.NewRequest(http.MethodGet, "/api/agents", nil)
	w := httptest.NewRecorder()
	h(w, r)
	if w.Code != 200 {
		t.Fatalf("status: %d", w.Code)
	}
	var agents []models.Agent
	json.NewDecoder(w.Body).Decode(&agents)
	if agents == nil {
		// tableau vide attendu, pas d'erreur
	}
}
