package suite

import (
	"bytes"
	"encoding/json"
	"net/http"

	"github.com/stretchr/testify/require"
)

// Do executes an http Request
func (s *Suite) Do(req *http.Request) (*http.Response, error) {
	req.Header.Add("X-Double-Cookie", s.doubleCookie)
	return s.Client.Do(req)
}

// Get is a helper for executing a GET request
func (s *Suite) Get(path string) *http.Response {
	resp, err := s.doWithoutData(http.MethodGet, path)
	require.NoError(s.t, err)
	return resp
}

// Delete is a helper for executing a DELETE request
func (s *Suite) Delete(path string) *http.Response {
	resp, err := s.doWithoutData(http.MethodDelete, path)
	require.NoError(s.t, err)
	return resp
}

// Post is a helper for executing a POST request with a JSON payload
func (s *Suite) Post(path string, payload interface{}) *http.Response {
	resp, err := s.doWithData(http.MethodPost, path, payload)
	require.NoError(s.t, err)
	return resp
}

// Put is a helper for executing a POST request with a JSON payload
func (s *Suite) Put(path string, payload interface{}) *http.Response {
	resp, err := s.doWithData(http.MethodPut, path, payload)
	require.NoError(s.t, err)
	return resp
}

// Patch is a helper for executing a PATCH request with a JSON payload
func (s *Suite) Patch(path string, payload interface{}) *http.Response {
	resp, err := s.doWithData(http.MethodPatch, path, payload)
	require.NoError(s.t, err)
	return resp
}

func (s *Suite) doWithData(method string, path string, payload interface{}) (*http.Response, error) {
	buf := &bytes.Buffer{}
	if err := json.NewEncoder(buf).Encode(payload); err != nil {
		return nil, err
	}
	req, err := http.NewRequest(method, s.PlatformURL(path), buf)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Content-Type", "application/json")
	return s.Do(req)
}

func (s *Suite) doWithoutData(method string, path string) (*http.Response, error) {
	req, err := http.NewRequest(method, s.PlatformURL(path), nil)
	if err != nil {
		return nil, err
	}
	return s.Do(req)

}
