// ui_repo_reinit.go — danger-zone re-init handler. Dispatches a fresh
// `restic init` job after the operator types the host name to confirm.
// Restic itself refuses to overwrite an existing repo (its init is
// effectively idempotent — see the runner's "config file already
// exists" sniff in restic.RunInit), so this is *not* a destructive
// data wipe; it's a "try again from scratch" affordance for the
// operator. If the rest-server bucket needs clearing the operator
// has to do that out-of-band; the job log will say so.
//
// Audit-logged with action='host.repo_reinit' so the trail records
// who triggered the wipe attempt and when.
package http

import (
	"context"
	"errors"
	"log/slog"
	stdhttp "net/http"
	"strings"
	"time"

	"github.com/oklog/ulid/v2"

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

func (s *Server) handleUIRepoReinit(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 err := r.ParseForm(); err != nil {
		stdhttp.Error(w, "bad request", stdhttp.StatusBadRequest)
		return
	}
	confirm := strings.TrimSpace(r.PostForm.Get("confirm_hostname"))
	if confirm != host.Name {
		// We don't have a dedicated re-init banner field; surface via
		// the existing CredentialsError slot — it sits adjacent to the
		// danger zone visually so the operator's eye lands on it.
		s.renderRepoPage(w, r, u, host,
			"Re-init aborted — typed hostname did not match.", "", "", "")
		return
	}
	if !s.deps.Hub.Connected(host.ID) {
		s.renderRepoPage(w, r, u, host,
			"Host is offline — bring the agent back up before re-initialising.",
			"", "", "")
		return
	}
	// Ensure the host has creds bound; otherwise restic init can't
	// connect to the repo.
	if _, err := s.deps.Store.GetHostCredentials(r.Context(), host.ID, store.CredKindRepo); err != nil {
		if errors.Is(err, store.ErrNotFound) {
			s.renderRepoPage(w, r, u, host,
				"Bind repo credentials before re-initialising.",
				"", "", "")
			return
		}
		stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
		return
	}

	jobID := ulid.Make().String()
	now := time.Now().UTC()
	if err := s.deps.Store.CreateJob(r.Context(), store.Job{
		ID:        jobID,
		HostID:    host.ID,
		Kind:      string(api.JobInit),
		ActorKind: "user",
		ActorID:   &u.ID,
		CreatedAt: now,
	}); err != nil {
		slog.Error("repo reinit: persist job", "host_id", host.ID, "err", err)
		stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
		return
	}

	env, err := api.Marshal(api.MsgCommandRun, jobID, api.CommandRunPayload{
		JobID: jobID,
		Kind:  api.JobInit,
	})
	if err != nil {
		stdhttp.Error(w, "internal", stdhttp.StatusInternalServerError)
		return
	}
	sendCtx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()
	if err := s.deps.Hub.Send(sendCtx, host.ID, env); err != nil {
		slog.Warn("repo reinit: ws send failed", "host_id", host.ID, "err", err)
		s.renderRepoPage(w, r, u, host,
			"Failed to deliver the init job to the agent — try again.",
			"", "", "")
		return
	}

	uid := u.ID
	_ = s.deps.Store.AppendAudit(r.Context(), store.AuditEntry{
		ID:         ulid.Make().String(),
		UserID:     &uid,
		Actor:      "user",
		Action:     "host.repo_reinit",
		TargetKind: ptr("host"),
		TargetID:   &host.ID,
		TS:         now,
	})

	// HTMX redirect → live job log. JSON callers get a 202.
	if wantsHTML(r) {
		w.Header().Set("HX-Redirect", "/jobs/"+jobID)
		w.WriteHeader(stdhttp.StatusNoContent)
		return
	}
	stdhttp.Redirect(w, r, "/jobs/"+jobID, stdhttp.StatusSeeOther)
}
