// ui_repo_probe_test.go — covers the NS-03 retry-probe handler: the
// 404 / offline-guarded path and the happy dispatch + audit + redirect.
package http

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

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

// TestRepoProbeOfflineRendersBanner: hitting probe for an offline
// host re-renders the repo page with a 422 banner; no init job lands.
func TestRepoProbeOfflineRendersBanner(t *testing.T) {
	t.Parallel()
	_, ts, st := rawTestServerWithUI(t)
	hostID, _ := enrolHostForUI(t, nil, st, "probe-offline-host")
	cookie := loginAsAdmin(t, st)

	req, _ := stdhttp.NewRequest("POST", ts.URL+"/hosts/"+hostID+"/repo/probe",
		strings.NewReader(""))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	res, err := stdhttp.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("do: %v", err)
	}
	defer res.Body.Close()
	if res.StatusCode != stdhttp.StatusUnprocessableEntity {
		t.Fatalf("status: got %d, want 422", res.StatusCode)
	}
	var n int
	if err := st.DB().QueryRow(
		`SELECT COUNT(*) FROM jobs WHERE host_id = ? AND kind = ? AND actor_kind = 'user'`,
		hostID, string(api.JobInit)).Scan(&n); err != nil {
		t.Fatalf("count jobs: %v", err)
	}
	if n != 0 {
		t.Errorf("user-actor init jobs: got %d, want 0 (offline guard bypassed)", n)
	}
}

// TestRepoProbeDispatchesWhenOnline: with the agent connected, a
// probe creates a user-actor init job and audits.
func TestRepoProbeDispatchesWhenOnline(t *testing.T) {
	t.Parallel()
	srv, ts, st := rawTestServerWithUI(t)
	hostID, token := enrolHostForUI(t, nil, st, "probe-ok-host")

	c := agentDial(t, srv, ts, hostID, token)
	sendHello(t, c, "probe-ok-host")
	_ = drainUntil(t, c, api.MsgScheduleSet)

	cookie := loginAsAdmin(t, st)

	form := url.Values{}
	req, _ := stdhttp.NewRequest("POST", ts.URL+"/hosts/"+hostID+"/repo/probe",
		strings.NewReader(form.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.AddCookie(cookie)
	cli := &stdhttp.Client{
		CheckRedirect: func(*stdhttp.Request, []*stdhttp.Request) error {
			return stdhttp.ErrUseLastResponse
		},
	}
	res, err := cli.Do(req)
	if err != nil {
		t.Fatalf("do: %v", err)
	}
	defer res.Body.Close()
	if res.StatusCode != stdhttp.StatusSeeOther {
		t.Fatalf("status: got %d, want 303", res.StatusCode)
	}
	if loc := res.Header.Get("Location"); !strings.Contains(loc, "saved=probe") {
		t.Errorf("Location: got %q, want saved=probe", loc)
	}

	var n int
	if err := st.DB().QueryRow(
		`SELECT COUNT(*) FROM jobs WHERE host_id = ? AND kind = ? AND actor_kind = 'user'`,
		hostID, string(api.JobInit)).Scan(&n); err != nil {
		t.Fatalf("count jobs: %v", err)
	}
	if n != 1 {
		t.Errorf("user-actor init jobs: got %d, want 1", n)
	}
	var auditN int
	if err := st.DB().QueryRow(
		`SELECT COUNT(*) FROM audit_log WHERE action = 'host.repo_init_dispatched' AND target_id = ?`,
		hostID).Scan(&auditN); err != nil {
		t.Fatalf("count audit: %v", err)
	}
	if auditN != 1 {
		t.Errorf("audit rows: got %d, want 1", auditN)
	}

	// Sanity: the host still exists and we can cleanly read repo status
	// (it stays "unknown" because the agent never replies in this test).
	host, err := st.GetHost(context.Background(), hostID)
	if err != nil {
		t.Fatalf("get host: %v", err)
	}
	if host.RepoStatus != "unknown" {
		t.Errorf("repo_status: got %q, want unknown (no probe reply yet)", host.RepoStatus)
	}
}
