package github

import (
	"fmt"
	"net/url"

	"code.justin.tv/common/config"
	"code.justin.tv/dta/rockpaperscissors/internal/sandstorm"
	gh "github.com/google/go-github/github"
	"github.com/pkg/errors"
	"golang.org/x/oauth2"
)

const (
	// The string format token is expanded with our environment name (e.g. "development", "production")
	oauthSecretName = "rps/rockpaperscissors/%s/github-oauth-token"
)

// Client is a convenience factory for making github Client structs.
func Client(sandstormClient sandstorm.ClientIface, host string) (*gh.Client, error) {
	secretName := fmt.Sprintf(oauthSecretName, config.Environment())

	oauthSecret, err := sandstormClient.Get(secretName)
	if err != nil {
		return nil, errors.Wrap(err,
			"Failed to get GitHub Access Token from Sandstorm")
	}

	ts := oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: string(oauthSecret.Plaintext)},
	)
	tc := oauth2.NewClient(oauth2.NoContext, ts)
	client := gh.NewClient(tc)
	client.UserAgent = fmt.Sprintf("%s-%s", config.App(), config.Environment())
	client.BaseURL = &url.URL{
		Scheme: "https",
		Host:   host,
		Path:   "/api/v3/",
	}

	return client, nil
}
