package client

import (
	"encoding/base64"
	"encoding/json"
	"net/http"
	"os/user"

	"github.com/pkg/errors"
)

type LDAPHeaderRoundTripper struct {
	username string
	group    string
	next     http.RoundTripper
}

func (l *LDAPHeaderRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	groups, err := encodeLDAPGroups([]string{l.group})
	if err != nil {
		return nil, errors.Wrap(err, "could not generate LDAP headers")
	}
	req.Header.Add("Twitch-Ldap-User", l.username)
	req.Header.Add("Twitch-Ldap-Groups", groups)
	return l.next.RoundTrip(req)
}

func ldapRoundTripper(next http.RoundTripper) http.RoundTripper {
	username, err := user.Current()
	if err != nil {
		panic(err)
	}
	return &LDAPHeaderRoundTripper{
		username: username.Username,
		group:    "team-eventbus",
		next:     next,
	}
}

// https://git-aws.internal.justin.tv/eventbus/controlplane/blob/master/internal/ldap/injector/injector.go#L43
func encodeLDAPGroups(groups []string) (string, error) {
	b, err := json.Marshal(groups)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}
