package auth

import (
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
)

// protectedResourceMetadata represents RFC 9728 OAuth 2.0 Protected Resource Metadata
type protectedResourceMetadata struct {
	Resource               string   `json:"resource"`
	AuthorizationServers   []string `json:"authorization_servers"`
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
}

// newProtectedResourceHandler creates an RFC 9728 compliant handler.
// Returns an error if required parameters are missing per RFC 9728:
// - resourceURL must not be empty
// - authorizationServers must contain at least one entry
func newProtectedResourceHandler(
	resourceURL string,
	authorizationServers []string,
) (http.Handler, error) {
	if len(authorizationServers) == 0 {
		return nil, errors.New("at least one authorization server is required")
	}

	return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		metadata := protectedResourceMetadata{
			Resource:               resourceURL,
			AuthorizationServers:   authorizationServers,
			BearerMethodsSupported: []string{"header"},
		}

		data, err := json.Marshal(metadata)
		if err != nil {
			slog.Error("Failed to encode protected resource metadata", "error", err)
			http.Error(w, `{"error":"internal server error"}`, http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(data)
	}), nil
}
