package httputil

import (
	"encoding/json"
	"io"
	"net/http"
	"regexp"
)

var bearerRe = regexp.MustCompile(`(?i)^Bearer\s+(.+)$`)

func ExtractBearerToken(r *http.Request) string {
	h := r.Header.Get("Authorization")
	if h == "" {
		return ""
	}
	m := bearerRe.FindStringSubmatch(h)
	if m == nil {
		return ""
	}
	return m[1]
}

func WriteJSON(w http.ResponseWriter, status int, body interface{}, extraHeaders map[string]string) {
	for k, v := range extraHeaders {
		w.Header().Set(k, v)
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(body)
}

func WriteSSEHeaders(w http.ResponseWriter, extraHeaders map[string]string) {
	for k, v := range extraHeaders {
		w.Header().Set(k, v)
	}
	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")
	w.Header().Set("X-Accel-Buffering", "no")
	w.WriteHeader(200)
}

func ReadBody(r *http.Request) (string, error) {
	data, err := io.ReadAll(r.Body)
	if err != nil {
		return "", err
	}
	return string(data), nil
}
