package web

import (
	"strings"
	"testing"
	"time"

	"gitea.dooplex.hu/admin/felhom-hub/internal/monitor"
)

// PBS DR panel — configured + ok: renders the datastore, capacity/used, fill bar.
func TestPBSDRPanel_OK(t *testing.T) {
	s, _ := newRenderServer(t)
	s.SetPBSDRBox(func() (monitor.PBSBoxSnapshot, bool) {
		return monitor.PBSBoxSnapshot{
			CapacityBytes: 40 * gib, UsedBytes: 8 * gib, FillPercent: 20, FillBand: "ok",
			State: monitor.PBSStateOK, FetchedAt: time.Now().UTC(),
		}, true
	})
	body := renderOffsite(t, s)
	for _, want := range []string{"PBS DR datastore", "felhom-offsite", "40.0 GB", "8.0 GB", "20% full"} {
		if !strings.Contains(body, want) {
			t.Fatalf("PBS DR panel missing %q", want)
		}
	}
}

// PBS DR panel — unavailable (endpoint script ≤ v1.1.0): the honest pending-update message, NOT a fake 0%.
func TestPBSDRPanel_Unavailable(t *testing.T) {
	s, _ := newRenderServer(t)
	s.SetPBSDRBox(func() (monitor.PBSBoxSnapshot, bool) {
		return monitor.PBSBoxSnapshot{State: monitor.PBSStateUnavailable, FetchedAt: time.Now().UTC()}, true
	})
	body := renderOffsite(t, s)
	if !strings.Contains(body, "usage not available") || !strings.Contains(body, "v1.2.0") {
		t.Fatalf("unavailable PBS panel must show the pending-update message:\n%s", pbsSection(body))
	}
	// Never a fake fill for the unavailable box.
	if strings.Contains(pbsSection(body), "% full") {
		t.Fatal("unavailable PBS panel must not render a fill percentage")
	}
}

// PBS DR panel — not configured (no tenantsync client).
func TestPBSDRPanel_NotConfigured(t *testing.T) {
	s, _ := newRenderServer(t)
	// s.pbsdrBox left nil
	body := renderOffsite(t, s)
	if !strings.Contains(body, "PBS DR metrics not configured") {
		t.Fatalf("unconfigured PBS panel must say 'not configured'")
	}
}

// pbsSection returns the slice of the body from the PBS DR datastore heading onward (for scoped asserts).
func pbsSection(body string) string {
	if i := strings.Index(body, "PBS DR datastore"); i >= 0 {
		return body[i:]
	}
	return body
}
