package ai

import (
	"net/http"
	"strings"

	app "haixun-backend/internal/library/errors"
	"haixun-backend/internal/library/errors/code"
)

func BearerToken(r *http.Request) (string, error) {
	auth := strings.TrimSpace(r.Header.Get("Authorization"))
	if auth == "" {
		return "", app.For(code.AI).InputMissingRequired("missing Authorization header")
	}

	const prefix = "Bearer "
	if !strings.HasPrefix(auth, prefix) {
		return "", app.For(code.Facade).InputInvalidFormat("Authorization must be a Bearer token")
	}

	token := strings.TrimSpace(strings.TrimPrefix(auth, prefix))
	if token == "" {
		return "", app.For(code.AI).InputMissingRequired("missing AI provider token")
	}
	return token, nil
}
