package handler

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestServeApps(t *testing.T) {
	// Index lists the tools.
	rec := httptest.NewRecorder()
	ServeApps(nil, rec, httptest.NewRequest(http.MethodGet, AppsVirtualPrefix, nil))
	if rec.Code != http.StatusOK {
		t.Fatalf("index: want 200, got %d", rec.Code)
	}
	if !strings.Contains(rec.Body.String(), "Classifier") {
		t.Errorf("index should list Classifier")
	}

	// A known tool resolves to HTML (embedded bytes may be empty in a fresh
	// checkout, so accept 200 with a body OR 404 only when the slot is empty).
	rec = httptest.NewRecorder()
	ServeApps(nil, rec, httptest.NewRequest(http.MethodGet, AppsVirtualPrefix+"classifier.html", nil))
	if rec.Code != http.StatusOK && rec.Code != http.StatusNotFound {
		t.Errorf("classifier.html: unexpected %d", rec.Code)
	}

	// Unknown name → 404.
	rec = httptest.NewRecorder()
	ServeApps(nil, rec, httptest.NewRequest(http.MethodGet, AppsVirtualPrefix+"nope.html", nil))
	if rec.Code != http.StatusNotFound {
		t.Errorf("unknown: want 404, got %d", rec.Code)
	}

	// Path traversal / subpath → 404.
	rec = httptest.NewRecorder()
	ServeApps(nil, rec, httptest.NewRequest(http.MethodGet, AppsVirtualPrefix+"a/b.html", nil))
	if rec.Code != http.StatusNotFound {
		t.Errorf("subpath: want 404, got %d", rec.Code)
	}
}
