// ui_repo_probe.go — NS-03 retry-probe handler. Re-dispatches an init
// job against a host so the operator can re-test creds / connectivity
// without typing the hostname (no destructive shape: restic init is
// idempotent against a populated repo, so this is safe to spam).
//
// On success the WS handler's job.finished hook flips repo_status
// back to "ready" (or "init_failed" with a fresh error message).
package http

import (
	"log/slog"
	stdhttp "net/http"
)

func (s *Server) handleUIRepoProbe(w stdhttp.ResponseWriter, r *stdhttp.Request) {
	u := s.requireUIUser(w, r)
	if u == nil {
		return
	}
	host, ok := s.loadHostForUI(w, r)
	if !ok {
		return
	}
	if s.deps.Hub == nil || !s.deps.Hub.Connected(host.ID) {
		s.renderRepoPage(w, r, u, host,
			"Host is offline — bring the agent back up before probing.",
			"", "", "")
		return
	}
	if err := s.dispatchInitJob(r.Context(), host.ID, "user", &u.ID); err != nil {
		slog.Warn("ui repo probe: dispatch", "host_id", host.ID, "err", err)
		s.renderRepoPage(w, r, u, host,
			"Probe dispatch failed — check the agent logs and try again.",
			"", "", "")
		return
	}
	stdhttp.Redirect(w, r, "/hosts/"+host.ID+"/repo?saved=probe", stdhttp.StatusSeeOther)
}
