package router_test

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

	"galaxy/game/internal/controller"
	"galaxy/game/internal/router"
	"galaxy/game/internal/router/handler"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestHealthzReturnsOKWithoutInit(t *testing.T) {
	r := router.SetupRouter(handler.NewDefaultConfigExecutor(func(p *controller.Param) {
		p.StoragePath = ""
	}))

	w := httptest.NewRecorder()
	req, _ := http.NewRequest(http.MethodGet, "/healthz", nil)
	r.ServeHTTP(w, req)

	require.Equal(t, http.StatusOK, w.Code, w.Body)

	var body map[string]string
	require.NoError(t, json.Unmarshal(w.Body.Bytes(), &body))
	assert.Equal(t, "ok", body["status"])
}

func TestResolveStoragePathPrecedence(t *testing.T) {
	t.Setenv("STORAGE_PATH", "/tmp/storage")
	t.Setenv("GAME_STATE_PATH", "/tmp/state")

	got, err := handler.ResolveStoragePath()
	require.NoError(t, err)
	assert.Equal(t, "/tmp/storage", got)
}

func TestResolveStoragePathFallback(t *testing.T) {
	t.Setenv("STORAGE_PATH", "")
	t.Setenv("GAME_STATE_PATH", "/tmp/state")

	got, err := handler.ResolveStoragePath()
	require.NoError(t, err)
	assert.Equal(t, "/tmp/state", got)
}

func TestResolveStoragePathMissing(t *testing.T) {
	t.Setenv("STORAGE_PATH", "")
	t.Setenv("GAME_STATE_PATH", "")

	_, err := handler.ResolveStoragePath()
	require.Error(t, err)
}
