// Package admin is the gateway's admin edge: HTTP Basic-Auth in front of a reverse
// proxy that forwards the operator's browser to the backend's server-rendered admin
// console under /_gm. The proxy is mounted at /_gm/ on the gateway's public listener
// (below the h2c wrap, see internal/connectsrv) and forwards verbatim — an inbound
// /_gm/<rest> reaches <backendURL>/_gm/<rest>, preserving the inbound Host so the
// backend's same-origin check sees the public origin. The backend trusts the gateway
// on this segment and adds the console's same-origin CSRF guard
// (docs/ARCHITECTURE.md §12).
package admin

import (
	"crypto/subtle"
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"

	"go.uber.org/zap"
)

// NewProxy returns a handler that checks Basic-Auth against user/password and
// reverse-proxies the request verbatim to the backend: the inbound path is
// preserved, so /_gm/<rest> reaches <backendURL>/_gm/<rest>. It is mounted at /_gm/
// on the gateway's public listener.
func NewProxy(backendURL, user, password string, log *zap.Logger) (http.Handler, error) {
	target, err := url.Parse(backendURL)
	if err != nil {
		return nil, fmt.Errorf("admin: parse backend url %q: %w", backendURL, err)
	}
	if log == nil {
		log = zap.NewNop()
	}
	proxy := &httputil.ReverseProxy{
		Rewrite: func(pr *httputil.ProxyRequest) {
			pr.SetURL(target)        // backend scheme+host; the inbound /_gm path is preserved
			pr.Out.Host = pr.In.Host // keep the public Host for the backend same-origin check
		},
		ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
			log.Warn("admin proxy upstream error", zap.String("path", r.URL.Path), zap.Error(err))
			w.WriteHeader(http.StatusBadGateway)
		},
	}
	return basicAuth(user, password, proxy), nil
}

// basicAuth wraps next with a constant-time Basic-Auth check.
func basicAuth(user, password string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		u, p, ok := r.BasicAuth()
		if !ok || !equal(u, user) || !equal(p, password) {
			w.Header().Set("WWW-Authenticate", `Basic realm="scrabble-admin"`)
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return
		}
		next.ServeHTTP(w, r)
	})
}

// equal compares two strings in constant time.
func equal(a, b string) bool {
	return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1
}
