package test_helper

import (
	"fmt"
	"io"
	"net/http"
)

type BearerAuthClient struct {
	token  string
	client *http.Client
}

func NewBearerAuthClient(token string) *BearerAuthClient {
	client := new(http.Client)
	return &BearerAuthClient{
		token, client,
	}
}

func (c *BearerAuthClient) newRequest(method, url string, body io.Reader) (*http.Request, error) {
	req, err := http.NewRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", c.token))
	return req, err
}

func (c *BearerAuthClient) Request(method, url string, body io.Reader) (*http.Response, error) {
	req, err := c.newRequest(method, url, body)
	if err != nil {
		return nil, err
	}
	return c.client.Do(req)
}

func (c *BearerAuthClient) Get(url string) (*http.Response, error) {
	req, err := c.newRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	return c.client.Do(req)
}

func (c *BearerAuthClient) Post(url string, contentType string, body io.Reader) (*http.Response, error) {
	req, err := c.newRequest("POST", url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", contentType)
	return c.client.Do(req)
}

func (c *BearerAuthClient) Put(url string, contentType string, body io.Reader) (*http.Response, error) {
	req, err := c.newRequest("PUT", url, body)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", contentType)
	return c.client.Do(req)
}