package http

import (
	"context"
	stdhttp "net/http"
	"strings"
	"testing"
	"time"

	"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
)

func getDashboard(t *testing.T, baseURL string, cookie *stdhttp.Cookie) string {
	t.Helper()
	client := &stdhttp.Client{
		CheckRedirect: func(_ *stdhttp.Request, _ []*stdhttp.Request) error {
			return stdhttp.ErrUseLastResponse
		},
	}
	req, err := stdhttp.NewRequest("GET", baseURL+"/", nil)
	if err != nil {
		t.Fatalf("new request: %v", err)
	}
	req.AddCookie(cookie)
	res, err := client.Do(req)
	if err != nil {
		t.Fatalf("GET /: %v", err)
	}
	defer res.Body.Close()
	if res.StatusCode != stdhttp.StatusOK {
		t.Fatalf("GET /: want 200, got %d", res.StatusCode)
	}
	body := make([]byte, 0, 1<<20)
	buf := make([]byte, 4096)
	for {
		n, rerr := res.Body.Read(buf)
		body = append(body, buf[:n]...)
		if rerr != nil {
			break
		}
	}
	return string(body)
}

func TestDashboard_HostRowSparklineRendersWithHistory(t *testing.T) {
	t.Parallel()
	_, baseURL, st := newTestServerWithUI(t)
	cookie := loginAsAdmin(t, st)
	hostID := makeHost(t, st, "h-spark")
	ctx := context.Background()

	// Two history points → polyline must render. Use dates relative to
	// now so the points always fall inside the dashboard's rolling
	// 30-day window (ui_handlers.go: since = now-30d); hard-coded dates
	// silently age out of the window and break this test over time.
	for i, day := range []string{
		time.Now().UTC().AddDate(0, 0, -2).Format("2006-01-02"),
		time.Now().UTC().AddDate(0, 0, -1).Format("2006-01-02"),
	} {
		v := int64(100 + i*50)
		if err := st.UpsertHostRepoStatsHistory(ctx, hostID, day,
			store.HostRepoStats{TotalSizeBytes: &v}, time.Now().UTC()); err != nil {
			t.Fatalf("upsert %s: %v", day, err)
		}
	}

	body := getDashboard(t, baseURL, cookie)
	if !strings.Contains(body, `class="repo-sparkline"`) {
		t.Errorf("expected sparkline SVG in dashboard body (class=repo-sparkline missing)")
	}
	if !strings.Contains(body, `<polyline`) {
		t.Errorf("expected <polyline> in dashboard body")
	}
}

func TestDashboard_HostRowSparklineEmptyState(t *testing.T) {
	t.Parallel()
	_, baseURL, st := newTestServerWithUI(t)
	cookie := loginAsAdmin(t, st)
	makeHost(t, st, "h-empty")

	body := getDashboard(t, baseURL, cookie)
	if !strings.Contains(body, `class="repo-sparkline"`) {
		t.Errorf("expected sparkline SVG element on dashboard")
	}
	if !strings.Contains(body, `>—<`) {
		t.Errorf("expected em-dash placeholder in empty sparkline cell")
	}
}
