package api

// PBS DR tier (SLICE 1): the agent-facing consume-once endpoint for the host's PBS token secret.
// The hub stored the secret at provision time (tenantsync → Store.SaveHostPBSSecret); the agent
// fetches it EXACTLY ONCE with its per-host key while applying the desired-state pbs_dr block
// (SLICE 2). The controller-side offsite consume endpoint is the precedent; this is its host-side
// twin. The secret value is never logged.

import (
	"database/sql"
	"encoding/json"
	"net/http"
)

// handleConsumePBSToken serves POST /api/v1/hosts/{host_id}/pbs/consume-token. Per-host key,
// self-scoped (the global key may consume on a host's behalf — the operator recovery path).
// 200 exactly once per stored secret; 404 when absent or already consumed; 403 on a foreign key.
func (h *Handler) handleConsumePBSToken(w http.ResponseWriter, r *http.Request, pathHostID string) {
	authHostID, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok {
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	if pathHostID == "" {
		http.Error(w, "Missing host_id", http.StatusBadRequest)
		return
	}
	if !isGlobal && authHostID != pathHostID {
		http.Error(w, "Forbidden: host_id mismatch", http.StatusForbidden)
		return
	}

	secret, err := h.store.ConsumeHostPBSSecret(pathHostID)
	if err == sql.ErrNoRows {
		http.Error(w, "No unconsumed PBS token secret for this host", http.StatusNotFound)
		return
	}
	if err != nil {
		h.logger.Printf("[ERROR] pbs consume-token %s: %v", pathHostID, err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	h.logger.Printf("[INFO] pbs token secret consumed by host %s (single-use; value withheld from logs)", pathHostID)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]string{"token_secret": secret})
}
