package api

// S1 offsite connectivity (doc 06 §3.2/§5): the operator admin surface for the WG endpoint
// record + peer registry. GLOBAL key ONLY on every route (the handleAdminSetDesiredState gate) —
// a per-host key must never author the peer list; the box-facing registration path is S2.
// DELETE takes the pubkey in the JSON body: WG pubkeys are std base64 ('/' and '+'), so a pubkey
// NEVER appears in a URL path — and no, URL-escaping is not the fix (see the S1 spec §8).

import (
	"context"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/netip"
	"strings"
	"time"

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

// WGSyncer is the reconciler seam (satisfied by *wgsync.Reconciler; tests inject a fake). nil =
// peer-sync disabled: mutations still hit the DB (the source of truth) and report sync:"disabled".
type WGSyncer interface {
	SyncNow(ctx context.Context) error
	Trigger()
}

// SetWGSyncer wires the wgsync reconciler (mirror of SetLatestVersionProvider; nil-safe).
func (h *Handler) SetWGSyncer(s WGSyncer) {
	h.wgSyncer = s
}

// validateWGPubkey enforces the exact WG public-key shape: 44 chars of std base64 decoding to
// 32 bytes. Anything else is rejected before any allocation.
func validateWGPubkey(pk string) error {
	if len(pk) != 44 {
		return fmt.Errorf("pubkey must be 44 base64 chars, got %d", len(pk))
	}
	raw, err := base64.StdEncoding.DecodeString(pk)
	if err != nil {
		return fmt.Errorf("pubkey is not valid base64: %v", err)
	}
	if len(raw) != 32 {
		return fmt.Errorf("pubkey must decode to 32 bytes, got %d", len(raw))
	}
	return nil
}

// validSSHAuthorizedKey does a conservative shape check on an SSH public key (an authorized_keys
// line): a known key type, a base64 blob, no newlines/control chars (it is written verbatim into a
// per-user authorized_keys file, so a hostile value must not inject options or extra lines).
func validSSHAuthorizedKey(line string) bool {
	line = strings.TrimSpace(line)
	if line == "" || strings.ContainsAny(line, "\n\r\x00") {
		return false
	}
	fields := strings.Fields(line)
	if len(fields) < 2 {
		return false
	}
	switch fields[0] {
	case "ssh-ed25519", "ssh-rsa", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", "ecdsa-sha2-nistp521", "sk-ssh-ed25519@openssh.com":
	default:
		return false
	}
	if _, err := base64.StdEncoding.DecodeString(fields[1]); err != nil {
		return false
	}
	return true
}

// syncAfterMutation runs an inline sync after a peer mutation. The DB write already happened —
// it is the source of truth — so a push failure is REPORTED, not rolled back: the reconciler's
// next tick converges the endpoint (Scenario D).
func (h *Handler) syncAfterMutation(ctx context.Context) string {
	if h.wgSyncer == nil {
		return "disabled"
	}
	syncCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()
	if err := h.wgSyncer.SyncNow(syncCtx); err != nil {
		h.logger.Printf("[ERROR] wgsync: inline push after mutation failed: %v (reconciler will retry)", err)
		h.wgSyncer.Trigger()
		return "deferred: " + err.Error()
	}
	return "ok"
}

// handleAdminSetWGEndpoint — PUT /admin/wg/endpoint. Upserts the endpoint record.
func (h *Handler) handleAdminSetWGEndpoint(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	var req struct {
		EndpointID   string `json:"endpoint_id"`
		DNSName      string `json:"dns_name"`
		WGPort       int    `json:"wg_port"`
		ServerPubkey string `json:"server_pubkey"`
		TunnelSubnet string `json:"tunnel_subnet"`
		PBSTunnelIP  string `json:"pbs_tunnel_ip"`
	}
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
		return
	}
	if req.DNSName == "" {
		http.Error(w, "Invalid payload: dns_name required", http.StatusBadRequest)
		return
	}
	if req.WGPort < 1 || req.WGPort > 65535 {
		http.Error(w, "Invalid payload: wg_port must be 1-65535", http.StatusBadRequest)
		return
	}
	if err := validateWGPubkey(req.ServerPubkey); err != nil {
		http.Error(w, "Invalid payload: server_pubkey: "+err.Error(), http.StatusBadRequest)
		return
	}
	prefix, err := netip.ParsePrefix(req.TunnelSubnet)
	if err != nil {
		http.Error(w, "Invalid payload: tunnel_subnet must be CIDR", http.StatusBadRequest)
		return
	}
	pbsAddr, err := netip.ParseAddr(req.PBSTunnelIP)
	if err != nil || !prefix.Contains(pbsAddr) {
		http.Error(w, "Invalid payload: pbs_tunnel_ip must be an address inside tunnel_subnet", http.StatusBadRequest)
		return
	}
	if err := h.store.SetWGEndpoint(&store.WGEndpoint{
		EndpointID: req.EndpointID, DNSName: req.DNSName, WGPort: req.WGPort,
		ServerPubkey: req.ServerPubkey, TunnelSubnet: req.TunnelSubnet, PBSTunnelIP: req.PBSTunnelIP,
	}); err != nil {
		h.logger.Printf("[ERROR] set wg endpoint: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	h.logger.Printf("[INFO] wg endpoint set: %s (%s:%d, subnet %s)", req.DNSName, req.DNSName, req.WGPort, req.TunnelSubnet)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(`{"status":"ok"}`))
}

// handleAdminGetWGEndpoint — GET /admin/wg/endpoint.
func (h *Handler) handleAdminGetWGEndpoint(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	e, err := h.store.GetWGEndpoint()
	if err == sql.ErrNoRows {
		http.Error(w, "wg endpoint not configured", http.StatusNotFound)
		return
	}
	if err != nil {
		h.logger.Printf("[ERROR] get wg endpoint: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"endpoint_id": e.EndpointID, "dns_name": e.DNSName, "wg_port": e.WGPort,
		"server_pubkey": e.ServerPubkey, "tunnel_subnet": e.TunnelSubnet, "pbs_tunnel_ip": e.PBSTunnelIP,
	})
}

// handleAdminAddWGPeer — POST /admin/wg/peers. Allocates a /32 (idempotent on pubkey) and
// pushes the full list inline (sync semantics: ok | deferred | disabled).
func (h *Handler) handleAdminAddWGPeer(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	var req struct {
		Pubkey string `json:"pubkey"`
		HostID string `json:"host_id"`
		Note   string `json:"note"`
	}
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
		return
	}
	if err := validateWGPubkey(req.Pubkey); err != nil {
		http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
		return
	}
	ip, existed, err := h.store.AddWGPeer(req.Pubkey, req.HostID, req.Note)
	if err == store.ErrWGEndpointUnset {
		http.Error(w, "wg endpoint not configured", http.StatusConflict)
		return
	}
	if err == store.ErrWGSubnetExhausted {
		http.Error(w, "tunnel subnet exhausted", http.StatusConflict)
		return
	}
	if err != nil {
		h.logger.Printf("[ERROR] add wg peer: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	syncStatus := h.syncAfterMutation(r.Context())
	h.logger.Printf("[INFO] wg peer added: %s -> %s/32 (existed=%v, sync=%s)", req.Pubkey, ip, existed, syncStatus)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"pubkey": req.Pubkey, "assigned_ip": ip + "/32", "existed": existed, "sync": syncStatus,
	})
}

// handleRegisterHostWG — POST /hosts/{host_id}/wg (S2, doc 06 §3.3 steps 2-4). The box-facing
// registration: per-host key SELF-SCOPED (the handleGetDesiredState gate; the global key may
// register on any host — the operator/DR path). Binds the pubkey to the host (idempotent /
// re-key-in-place / adopt-unbound per the store), and ONLY on a real change bumps the host's
// desired_generation + pushes the peer list to the endpoint.
func (h *Handler) handleRegisterHostWG(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
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	var req struct {
		Pubkey string `json:"pubkey"`
	}
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
		return
	}
	if err := validateWGPubkey(req.Pubkey); err != nil {
		http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
		return
	}
	host, err := h.store.GetHost(pathHostID)
	if err != nil {
		h.logger.Printf("[ERROR] wg register: host lookup %s: %v", pathHostID, err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	if host == nil {
		http.Error(w, "Unknown host_id", http.StatusNotFound)
		return
	}

	ip, changed, err := h.store.RegisterWGPeerForHost(pathHostID, req.Pubkey)
	switch {
	case err == store.ErrWGEndpointUnset:
		http.Error(w, "wg endpoint not configured", http.StatusConflict)
		return
	case err == store.ErrWGPubkeyBoundElsewhere:
		http.Error(w, "pubkey already registered elsewhere", http.StatusConflict)
		return
	case err == store.ErrWGSubnetExhausted:
		http.Error(w, "tunnel subnet exhausted", http.StatusConflict)
		return
	case err != nil:
		h.logger.Printf("[ERROR] wg register %s: %v", pathHostID, err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}

	gen := host.DesiredGeneration
	syncStatus := "unchanged"
	if changed {
		gen, err = h.store.BumpHostDesired(pathHostID)
		if err != nil {
			h.logger.Printf("[ERROR] wg register %s: generation bump: %v", pathHostID, err)
			http.Error(w, "Internal error", http.StatusInternalServerError)
			return
		}
		syncStatus = h.syncAfterMutation(r.Context())
		// v0.51.0 DR-tier cascade (scenario A): a NEW tunnel peer may be the pbs_dr descriptor's
		// last unmet precondition — fire the hook so a DR-ON customer provisions hands-free.
		// Detached goroutine: registration must never wait on (or fail over) ep0 provisioning;
		// the hook itself detaches+bounds its context and logs every outcome.
		if h.wgRegisteredHook != nil && host.CustomerID != "" {
			go h.wgRegisteredHook(context.WithoutCancel(r.Context()), host.CustomerID)
		}
	}
	h.logger.Printf("[INFO] wg registered: host=%s pubkey=%s ip=%s/32 changed=%v gen=%d sync=%s",
		pathHostID, req.Pubkey, ip, changed, gen, syncStatus)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"pubkey": req.Pubkey, "assigned_ip": ip + "/32", "existed": !changed,
		"generation": gen, "sync": syncStatus,
	})
}

// mergeWireguard injects the hub-OWNED wireguard block into a host's served desired-state (S2
// merge-at-read: the stored desired_json stays a pure operator blob; the WG assignment is hub
// state and is merged only on the way out). No peer → the blob passes through untouched (the
// golden pass-through contract). Any merge failure is fail-safe: log + serve UNMERGED — never
// break the agent's control channel over the WG add-on.
//
// Deliberately NOT wire fields (S3 agent constants derived from the design + pbs_tunnel_ip):
// client-side AllowedIPs, PersistentKeepalive=25, MTU 1420.
func (h *Handler) mergeWireguard(hostID, desired string) string {
	peer, err := h.store.GetWGPeerForHost(hostID)
	if err == sql.ErrNoRows {
		return desired // no peer — byte-identical pass-through
	}
	if err != nil {
		h.logger.Printf("[ERROR] wg merge %s: peer lookup: %v (serving unmerged)", hostID, err)
		return desired
	}
	ep, err := h.store.GetWGEndpoint()
	if err != nil {
		h.logger.Printf("[ERROR] wg merge %s: peer exists but endpoint record unreadable: %v (serving unmerged)", hostID, err)
		return desired
	}
	var doc map[string]interface{}
	if err := json.Unmarshal([]byte(desired), &doc); err != nil {
		h.logger.Printf("[ERROR] wg merge %s: stored desired_json unparsable: %v (serving unmerged)", hostID, err)
		return desired
	}
	wgBlock := map[string]interface{}{
		"endpoint": map[string]interface{}{
			"dns_name":      ep.DNSName,
			"wg_port":       ep.WGPort,
			"server_pubkey": ep.ServerPubkey,
			"pbs_tunnel_ip": ep.PBSTunnelIP,
		},
		"pubkey":      peer.Pubkey,
		"assigned_ip": peer.AssignedIP + "/32",
	}
	// H1 [OF-1]: if a fleet operator OOB peer is registered, deliver its tunnel /32 as oob_peer_ip so
	// the agent RENDERS it into wg-felhom AllowedIPs (survives self-heal). Absent → key omitted →
	// byte-identical pass-through for pre-H1 fleets. A lookup failure is fail-safe (serve without OOB,
	// never break the control channel).
	if op, oerr := h.store.GetOperatorOOBPeer(); oerr != nil {
		h.logger.Printf("[WARN] wg merge %s: operator OOB peer lookup failed: %v (serving without oob_peer_ip)", hostID, oerr)
	} else if op != nil {
		wgBlock["oob_peer_ip"] = op.AssignedIP // bare IPv4, e.g. "10.77.0.250"
		// The operator SSH pubkey rides alongside (agent writes felhom-sshd's authorized_keys from it).
		if k := h.store.GetOOBOperatorSSHKey(); k != "" {
			wgBlock["oob_operator_ssh_key"] = k
		}
	}
	doc["wireguard"] = wgBlock
	out, err := json.Marshal(doc)
	if err != nil {
		h.logger.Printf("[ERROR] wg merge %s: re-marshal: %v (serving unmerged)", hostID, err)
		return desired
	}
	return string(out)
}

// handleAdminDeleteWGPeer — DELETE /admin/wg/peers, pubkey in the JSON body (never the URL).
// Unknown pubkey → 404 with NO sync (nothing changed). Known → delete + inline push: the pushed
// full list no longer contains the peer, so revocation lands with the push (Scenario B).
func (h *Handler) handleAdminDeleteWGPeer(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	var req struct {
		Pubkey string `json:"pubkey"`
	}
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
		return
	}
	if err := validateWGPubkey(req.Pubkey); err != nil {
		http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
		return
	}
	// S2: a BOUND peer's host must learn its block is gone — read the owner before deleting so
	// the delete can bump that host's generation (an unbound S1 row bumps nothing).
	ownerHostID := ""
	if peers, err := h.store.ListWGPeers(); err == nil {
		for _, p := range peers {
			if p.Pubkey == req.Pubkey {
				ownerHostID = p.HostID
				break
			}
		}
	}
	err = h.store.RemoveWGPeer(req.Pubkey)
	if err == sql.ErrNoRows {
		http.Error(w, "Unknown pubkey", http.StatusNotFound)
		return
	}
	if err != nil {
		h.logger.Printf("[ERROR] remove wg peer: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	if ownerHostID != "" {
		if gen, err := h.store.BumpHostDesired(ownerHostID); err != nil {
			h.logger.Printf("[ERROR] wg delete: generation bump for %s: %v", ownerHostID, err)
		} else {
			h.logger.Printf("[INFO] wg delete: host %s generation -> %d (peer unbound)", ownerHostID, gen)
		}
	}
	syncStatus := h.syncAfterMutation(r.Context())
	h.logger.Printf("[INFO] wg peer removed: %s (sync=%s)", req.Pubkey, syncStatus)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{"status": "ok", "sync": syncStatus})
}

// handleAdminListWGPeers — GET /admin/wg/peers. The verification surface (S2 builds UI on top).
func (h *Handler) handleAdminListWGPeers(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	peers, err := h.store.ListWGPeers()
	if err != nil {
		h.logger.Printf("[ERROR] list wg peers: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	out := make([]map[string]interface{}, 0, len(peers))
	for _, p := range peers {
		out = append(out, map[string]interface{}{
			"pubkey": p.Pubkey, "assigned_ip": p.AssignedIP + "/32", "host_id": p.HostID, "note": p.Note,
		})
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{"peers": out})
}

// handleAdminSetOperatorPeer — PUT /admin/wg/operator-peer (global key). Registers/rotates the fleet
// operator OOB peer at an EXPLICIT /32 (so the endpoint's static forward chain can hardcode it),
// pushes the full peer list to the endpoint (so the operator's handshake is accepted), and bumps
// EVERY host's generation so agents re-fetch + re-render oob_peer_ip into wg-felhom AllowedIPs (H1).
func (h *Handler) handleAdminSetOperatorPeer(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
	if err != nil {
		http.Error(w, "Bad request", http.StatusBadRequest)
		return
	}
	var req struct {
		Pubkey     string `json:"pubkey"`
		AssignedIP string `json:"assigned_ip"` // bare IPv4, e.g. "10.77.0.250"
		SSHPubkey  string `json:"ssh_pubkey"`  // optional: the operator's SSH authorized_keys line
	}
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "Invalid payload: body must be JSON", http.StatusBadRequest)
		return
	}
	if err := validateWGPubkey(req.Pubkey); err != nil {
		http.Error(w, "Invalid payload: "+err.Error(), http.StatusBadRequest)
		return
	}
	if req.SSHPubkey != "" && !validSSHAuthorizedKey(req.SSHPubkey) {
		http.Error(w, "Invalid payload: ssh_pubkey must be an ssh-ed25519/ssh-rsa/ecdsa authorized_keys line", http.StatusBadRequest)
		return
	}
	if err := h.store.SetOperatorOOBPeer(req.Pubkey, req.AssignedIP); err != nil {
		if err == store.ErrWGEndpointUnset {
			http.Error(w, "wg endpoint not configured", http.StatusConflict)
			return
		}
		http.Error(w, "Invalid operator peer: "+err.Error(), http.StatusBadRequest)
		return
	}
	if req.SSHPubkey != "" {
		if err := h.store.SetOOBOperatorSSHKey(req.SSHPubkey); err != nil {
			h.logger.Printf("[WARN] operator peer set but ssh_pubkey store failed: %v", err)
		}
	}
	syncStatus := h.syncAfterMutation(r.Context())
	bumped, berr := h.store.BumpAllHostGenerations()
	if berr != nil {
		h.logger.Printf("[WARN] operator peer set but generation bump failed: %v", berr)
	} else if h.poker != nil {
		h.poker.PokeAllHosts() // agent-plane immediate-sync (Direction-2a): every host generation moved → fleet nudge (fire-after-commit)
	}
	h.logger.Printf("[INFO] operator OOB peer set: %s -> %s/32 (sync=%s, %d host generations bumped)",
		req.Pubkey, req.AssignedIP, syncStatus, bumped)
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"pubkey": req.Pubkey, "assigned_ip": req.AssignedIP + "/32", "sync": syncStatus, "hosts_bumped": bumped,
	})
}

// handleAdminGetOperatorPeer — GET /admin/wg/operator-peer (global key). Read-back for the runbook
// (the operator /32 the endpoint's static forward chain must allow). 404 when none registered.
func (h *Handler) handleAdminGetOperatorPeer(w http.ResponseWriter, r *http.Request) {
	_, _, isGlobal, ok := h.checkAuthHost(r)
	if !ok || !isGlobal {
		http.Error(w, "Forbidden: global key required", http.StatusForbidden)
		return
	}
	op, err := h.store.GetOperatorOOBPeer()
	if err != nil {
		h.logger.Printf("[ERROR] get operator peer: %v", err)
		http.Error(w, "Internal error", http.StatusInternalServerError)
		return
	}
	if op == nil {
		http.Error(w, "No operator OOB peer registered", http.StatusNotFound)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"pubkey": op.Pubkey, "assigned_ip": op.AssignedIP + "/32",
	})
}
