package suite

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

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

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

func (s *Suite) Get(path string) *http.Response {
	resp, err := s.doWithoutData(http.MethodGet, path)
	require.NoError(s.t, err)
	return resp
}

func (s *Suite) Delete(path string) *http.Response {
	resp, err := s.doWithoutData(http.MethodDelete, path)
	require.NoError(s.t, err)
	return resp
}

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
}

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
}

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)

}
