package middlewares

import (
	"context"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type HeaderExtractorMiddleware struct{}

func NewHeaderExtractorMiddleware() *HeaderExtractorMiddleware {
	return &HeaderExtractorMiddleware{}
}

func (m *HeaderExtractorMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		logx.Infof(
			"headerExtractorMiddleware method=%s path=%s requestId=%s hasUserId=%t hasIsAdmin=%t hasCookie=%t",
			r.Method,
			r.URL.Path,
			r.Header.Get("x-request-id"),
			r.Header.Get("x-auth-user-id") != "",
			r.Header.Get("x-auth-is-admin") != "",
			r.Header.Get("cookie") != "",
		)

		ctx := r.Context()

		if userID := r.Header.Get("x-auth-user-id"); userID != "" {
			if parsed, err := strconv.ParseInt(userID, 10, 64); err == nil {
				ctx = context.WithValue(ctx, "user_id", parsed)
			} else {
				logx.Errorf("invalid x-auth-user-id header: %v", err)
			}
		}

		if isAdmin := r.Header.Get("x-auth-is-admin"); isAdmin != "" {
			if parsed, err := strconv.ParseBool(isAdmin); err == nil {
				ctx = context.WithValue(ctx, "is_admin", parsed)
			} else {
				logx.Errorf("invalid x-auth-is-admin header: %v", err)
			}
		}

		if requestID := r.Header.Get("x-request-id"); requestID != "" {
			ctx = context.WithValue(ctx, "request_id", requestID)
			ctx = context.WithValue(ctx, "rid", requestID)
		}

		next(w, r.WithContext(ctx))
	}
}
