// Code generated by protoc-gen-go-flipt-sdk. DO NOT EDIT.

package http

import (
	_go "go.flipt.io/flipt/sdk/go"
	status "google.golang.org/genproto/googleapis/rpc/status"
	metadata "google.golang.org/grpc/metadata"
	status1 "google.golang.org/grpc/status"
	protojson "google.golang.org/protobuf/encoding/protojson"
	http "net/http"
)

var _ _go.Transport = Transport{}

type Transport struct {
	client *http.Client
	addr   string
}

type Option func(*Transport)

func WithHTTPClient(client *http.Client) Option {
	return func(t *Transport) { t.client = client }
}

func NewTransport(addr string, opts ...Option) Transport {
	t := Transport{
		client: &http.Client{Transport: http.DefaultTransport},
		addr:   addr,
	}
	for _, opt := range opts {
		opt(&t)
	}
	transport := t.client.Transport
	t.client.Transport = roundTripFunc(func(r *http.Request) (*http.Response, error) {
		md, ok := metadata.FromOutgoingContext(r.Context())
		if ok {
			if auth := md.Get("authorization"); len(auth) > 0 {
				r.Header.Set("Authorization", auth[0])
			}
		}

		return transport.RoundTrip(r)
	})

	return t
}

func checkResponse(resp *http.Response, v []byte) error {
	if resp.StatusCode != http.StatusOK {
		var status status.Status
		if err := protojson.Unmarshal(v, &status); err != nil {
			return err
		}
		return status1.ErrorProto(&status)
	}

	return nil
}

type roundTripFunc func(r *http.Request) (*http.Response, error)

func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
	return f(r)
}
