package main

import (
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/gin-gonic/gin"
)

func TestInstalledFrontendDocumentationAssets(t *testing.T) {
	dir := t.TempDir()
	files := map[string]string{
		"index.html":               "<!doctype html><title>ChatLoop</title>",
		"vendor/scalar-1.59.3.js":  "window.Scalar = { createApiReference() {} };",
		"assets/app.js":            "console.log('dashboard');",
		"opus/OggOpusEncoder.wasm": "wasm-fixture",
	}
	for name, body := range files {
		filename := filepath.Join(dir, name)
		if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
			t.Fatal(err)
		}
		if err := os.WriteFile(filename, []byte(body), 0600); err != nil {
			t.Fatal(err)
		}
	}
	router := gin.New()
	registerFrontendRoutes(router, dir)
	for _, tc := range []struct {
		path     string
		code     int
		contains string
		mime     string
	}{
		{"/vendor/scalar-1.59.3.js", 200, "window.Scalar", "javascript"},
		{"/vendor/missing.js", 404, "", ""},
		{"/assets/app.js", 200, "dashboard", "javascript"},
		{"/opus/OggOpusEncoder.wasm", 200, "wasm-fixture", "application/wasm"},
		{"/api/missing", 404, "not found", "application/json"},
		{"/app", 200, "ChatLoop", "text/html"},
	} {
		t.Run(tc.path, func(t *testing.T) {
			response := httptest.NewRecorder()
			router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, tc.path, nil))
			if response.Code != tc.code || !strings.Contains(response.Body.String(), tc.contains) || !strings.Contains(response.Header().Get("Content-Type"), tc.mime) {
				t.Fatalf("%s: status=%d content-type=%q body=%q", tc.path, response.Code, response.Header().Get("Content-Type"), response.Body.String())
			}
			if tc.code == 404 && strings.Contains(response.Body.String(), "<!doctype html>") {
				t.Fatal("Missing asset must not return the SPA document")
			}
		})
	}
}
