package license

import (
	"fmt"
	"net/http"
	"strings"
	"time"
)

// Middleware 按租约文件判断是否过期。授权控制接口始终放行，便于过期后远端续费/延期。
func Middleware(m *Manager) func(http.HandlerFunc) http.HandlerFunc {
	return func(next http.HandlerFunc) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			path := r.URL.Path
			if isLicenseControlPath(path) || isHealthPath(path) {
				next(w, r)
				return
			}
			if m == nil || !m.Enabled() {
				next(w, r)
				return
			}
			st := m.Status(time.Now())
			if !st.Expired {
				next(w, r)
				return
			}
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			w.WriteHeader(http.StatusPaymentRequired)
			_, _ = w.Write([]byte(fmt.Sprintf(
				`{"error":%q,"code":"license_expired","extensions_remaining":%d}`,
				st.Message, st.ExtensionsRemaining,
			)))
		}
	}
}

func isHealthPath(path string) bool {
	return path == "/ping" || path == "/healthz" || strings.HasSuffix(path, "/healthz")
}

func isLicenseControlPath(path string) bool {
	return strings.HasPrefix(path, "/api/v1/license/")
}
