package server

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

	"git.mchus.pro/mchus/logpile/internal/models"
)

func TestHandleChartCurrent_RendersCurrentReanimatorSnapshot(t *testing.T) {
	s := New(Config{})
	s.SetResult(&models.AnalysisResult{
		SourceType:  models.SourceTypeArchive,
		Filename:    "example.zip",
		CollectedAt: time.Date(2026, 3, 16, 10, 0, 0, 0, time.UTC),
		Hardware: &models.HardwareConfig{
			BoardInfo: models.BoardInfo{
				ProductName:  "SYS-TEST",
				SerialNumber: "SN123",
			},
			CPUs: []models.CPU{
				{
					Socket: 1,
					Model:  "Xeon Gold",
					Cores:  32,
				},
			},
		},
	})

	req := httptest.NewRequest(http.MethodGet, "/chart/current", nil)
	rec := httptest.NewRecorder()

	s.mux.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "SYS-TEST - SN123") {
		t.Fatalf("expected chart title in body, got %q", body)
	}
	if !strings.Contains(body, `/chart/static/view.css`) {
		t.Fatalf("expected rewritten chart static path, got %q", body)
	}
	if !strings.Contains(body, "Snapshot Metadata") {
		t.Fatalf("expected rendered chart output, got %q", body)
	}
}

func TestHandleChartCurrent_RendersEmptyViewerWithoutResult(t *testing.T) {
	s := New(Config{})

	req := httptest.NewRequest(http.MethodGet, "/chart/current", nil)
	rec := httptest.NewRecorder()

	s.mux.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d", rec.Code)
	}
	body := rec.Body.String()
	if !strings.Contains(body, "Snapshot Viewer") {
		t.Fatalf("expected empty chart viewer, got %q", body)
	}
}
