package users

import (
	"context"
	"net/http"

	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	"code.justin.tv/live/autohost/internal/metrics"

	"code.justin.tv/creator-collab/log/errors"
	"code.justin.tv/foundation/twitchclient"
	"code.justin.tv/web/users-service/client/usersclient_internal"
	"code.justin.tv/web/users-service/models"
	"github.com/cactus/go-statsd-client/statsd"
)

const metricsServiceName = "Users"

type Client interface {
	GetUserByID(ctx context.Context, userID string, reqOpts *twitchclient.ReqOpts) (*models.Properties, error)
}

func NewClient(url string, statsClient statsd.Statter, sampleReporter *telemetry.SampleReporter) (Client, error) {
	client, err := usersclient_internal.NewClient(twitchclient.ClientConf{
		Host:           url,
		Stats:          statsClient,
		TimingXactName: "users_service",
		Transport: twitchclient.TransportConf{
			MaxIdleConnsPerHost: 10,
		},
		RoundTripperWrappers: []func(http.RoundTripper) http.RoundTripper{
			metrics.NewTwitchClientMiddlewareWrapper(&metrics.TwitchClientMiddlewareWrapperConfig{
				SampleReporter: sampleReporter,
			}),
		},
	})
	if err != nil {
		return nil, errors.Wrap(err, "users service - creating client failed")
	}

	return &clientImpl{
		inner: client,
	}, nil
}

type clientImpl struct {
	inner usersclient_internal.InternalClient
}

func (s *clientImpl) GetUserByID(ctx context.Context, userID string, reqOpts *twitchclient.ReqOpts) (*models.Properties, error) {
	ctx = metrics.WithTwitchClientOperation(ctx, metricsServiceName, "GetUserByID")

	result, err := s.inner.GetUserByID(ctx, userID, nil)
	if err != nil {
		return nil, errors.Wrap(err, "users service - GetUserByID failed", errors.Fields{
			"user_id": userID,
		})
	}

	return result, nil
}
