package oauth

import (
	"encoding/base64"
	"encoding/json"
	"net/http"

	"gitea.local/admin/hspguard/internal/util"
	"gitea.local/admin/hspguard/internal/web"
)

func (h *OAuthHandler) WriteJWKS(w http.ResponseWriter, r *http.Request) {
	pubKey, err := util.ParseBase64PublicKey(h.cfg.Jwt.PublicKey)
	if err != nil {
		web.Error(w, "failed to parse public key", http.StatusInternalServerError)
	}

	n := base64.RawURLEncoding.EncodeToString(pubKey.N.Bytes())
	e := base64.RawURLEncoding.EncodeToString([]byte{1, 0, 1}) // 65537 = 0x010001

	jwks := map[string]interface{}{
		"keys": []map[string]string{
			{
				"kty": "RSA",
				"kid": "my-rsa-key-1",
				"use": "sig",
				"alg": "RS256",
				"n":   n,
				"e":   e,
			},
		},
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(jwks)
}
