package hallpass

import (
	"context"
	"net/http"

	telemetry "code.justin.tv/amzn/TwitchTelemetry"
	"code.justin.tv/cb/hallpass/client/hallpass"
	"code.justin.tv/cb/hallpass/view"
	"code.justin.tv/creator-collab/log/errors"
	"code.justin.tv/foundation/twitchclient"
	"code.justin.tv/live/autohost/internal/metrics"
	"github.com/cactus/go-statsd-client/statsd"
)

const metricsServiceName = "Hallpass"

type Client interface {
	GetV1IsEditor(ctx context.Context, channelID string, editorID string, reqOpts *twitchclient.ReqOpts) (*view.GetIsEditorResponse, error)
}

func NewClient(url string, statsClient statsd.Statter, sampleReporter *telemetry.SampleReporter) (Client, error) {
	client, err := hallpass.NewClient(twitchclient.ClientConf{
		Host:           url,
		Stats:          statsClient,
		TimingXactName: "hallpass",
		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, "hallpass - creating client failed")
	}

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

type clientImpl struct {
	inner hallpass.Client
}

func (s *clientImpl) GetV1IsEditor(ctx context.Context, channelID string, editorID string, reqOpts *twitchclient.ReqOpts) (*view.GetIsEditorResponse, error) {
	ctx = metrics.WithTwitchClientOperation(ctx, metricsServiceName, "GetV1IsEditor")

	result, err := s.inner.GetV1IsEditor(ctx, channelID, editorID, reqOpts)
	if err != nil {
		return nil, errors.Wrap(err, "hallpass - check if editor failed", errors.Fields{
			"channel_id": channelID,
			"editor_id":  editorID,
		})
	}

	return result, nil
}
