package kong

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type OpenAPIAuthResult struct {
	PublicKey string   `json:"public_key"`
	CIDRs     []string `json:"cidrs,omitempty"`
}

// Retrieve open API related auth info from headers, These headers are added by kong, which perform digest auth for open API.
// The design doc is https://pingcap.feishu.cn/wiki/wikcnETVg3f9BdyFvRuG3WPniPh
func GetOpenAPIAuthResult(r *http.Request) (*OpenAPIAuthResult, error) {
	authType := r.Header.Get("X-Auth-Type")
	if authType != string(AuthTypeOpenAPI) {
		return nil, fmt.Errorf("unexpected auth type: %s", authType)
	}

	authContent := r.Header.Get("X-Auth-Content")
	result := new(OpenAPIAuthResult)
	err := json.Unmarshal([]byte(authContent), result)
	if err != nil {
		return nil, fmt.Errorf("failed to unmarshal: auth content: %s, error: %s", authContent, err)
	}
	if result.PublicKey == "" {
		return nil, fmt.Errorf("failed to retrieve public_key: auth content: %s", authContent)
	}
	return result, nil
}
