package errortracking

import (
	"net/http"

	"github.com/getsentry/sentry-go"

	"gitlab.com/gitlab-org/labkit/mask"
)

// WithRequest will capture details of the request along with the error
func WithRequest(r *http.Request) CaptureOption {
	return func(event *sentry.Event) {
		event.Request = redactRequestInfo(r)
		event.Request.URL = r.URL.String()
		event.Request.Headers["host"] = r.URL.Hostname()
		event.Request.Method = r.Method
	}
}

// redactRequestInfo strips out information that shouldn't be send by the client
func redactRequestInfo(r *http.Request) sentry.Request {
	if r == nil {
		return sentry.Request{}
	}

	req := sentry.Request{
		Headers: make(map[string]string),
	}

	for header, v := range r.Header {
		req.Headers[header] = v[0]
		if mask.IsSensitiveHeader(header) {
			req.Headers[header] = mask.RedactionString
		}
	}

	params := r.URL.Query()
	for paramName := range params {
		if mask.IsSensitiveParam(paramName) {
			for i := range params[paramName] {
				params[paramName][i] = mask.RedactionString
			}
		}
	}
	req.QueryString = params.Encode()

	return req
}
