package injector

import (
	"encoding/base64"
	"encoding/json"
	"net/http"
)

// LDAPHeaderInjector injects the LDAP headers for scripts and command-line applications.
type LDAPHeaderInjector struct {
	name   string
	groups []string
	next   http.RoundTripper
}

func NewLDAPHeaderInjector(name string, next http.RoundTripper) *LDAPHeaderInjector {
	return &LDAPHeaderInjector{
		name:   name,
		groups: make([]string, 0), //empty by default unless overridden
		next:   next,
	}
}

func (l *LDAPHeaderInjector) WithGroups(groups []string) *LDAPHeaderInjector {
	l.groups = groups
	return l
}

func (l *LDAPHeaderInjector) RoundTrip(r *http.Request) (*http.Response, error) {
	if r.Header == nil {
		r.Header = make(http.Header)
	}
	groups, err := encodeLDAPGroups(l.groups)
	if err != nil {
		return nil, err
	}
	r.Header.Set("Twitch-Ldap-User", l.name)
	r.Header.Set("Twitch-Ldap-Groups", groups)
	return l.next.RoundTrip(r)
}

// converts a list of strings into a base64 encoded JSON representation
func encodeLDAPGroups(groups []string) (string, error) {
	b, err := json.Marshal(groups)
	if err != nil {
		return "", err
	}
	return base64.StdEncoding.EncodeToString(b), nil
}
