package control

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

	cfgpkg "github.com/jan/fm-rds-tx/internal/config"
)

func TestHealthz(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
	if rec.Code != 200 { t.Fatalf("status: %d", rec.Code) }
}

func TestStatus(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/status", nil))
	if rec.Code != 200 { t.Fatalf("status: %d", rec.Code) }
	var body map[string]any
	json.Unmarshal(rec.Body.Bytes(), &body)
	if body["service"] != "fm-rds-tx" { t.Fatal("missing service") }
	if _, ok := body["preEmphasisTauUS"]; !ok { t.Fatal("missing preEmphasisTauUS") }
}

func TestDryRunEndpoint(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/dry-run", nil))
	if rec.Code != 200 { t.Fatalf("status: %d", rec.Code) }
	var body map[string]any
	json.Unmarshal(rec.Body.Bytes(), &body)
	if body["mode"] != "dry-run" { t.Fatal("wrong mode") }
}

func TestConfigPatch(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	body := []byte(`{"toneLeftHz":900,"radioText":"hello world","preEmphasisTauUS":75}`)
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/config", bytes.NewReader(body)))
	if rec.Code != 200 { t.Fatalf("status: %d body=%s", rec.Code, rec.Body.String()) }
}

func TestRuntimeWithoutDriver(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/runtime", nil))
	if rec.Code != 200 { t.Fatalf("status: %d", rec.Code) }
}

func TestTXStartWithoutController(t *testing.T) {
	srv := NewServer(cfgpkg.Default())
	rec := httptest.NewRecorder()
	srv.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/tx/start", nil))
	if rec.Code != http.StatusServiceUnavailable { t.Fatalf("expected 503, got %d", rec.Code) }
}
