package client

import (
	"context"

	"github.com/go-resty/resty/v2"
)

func buildRequest(ctx context.Context, settings *RequestSettings) *resty.Request {
	request := resty.New().R().SetContext(ctx)

	if settings == nil {
		return request
	}

	if settings.Body != nil {
		request.SetBody(settings.Body)
	}

	if settings.QueryParams != nil {
		request.SetQueryParams(settings.QueryParams)
	}

	request.SetHeaders(settings.Headers)

	return request
}

func makeRequest[T any, R any](url string, requestMethod func(url string) (*resty.Response, error)) (*Response[T, R], error) {
	responseInstance, err := requestMethod(url)
	if err != nil {
		return nil, err
	}

	if responseInstance.IsError() {
		responseBody, parseErr := parseResponse[R](responseInstance.Body(), responseInstance.RawResponse)
		if parseErr != nil {
			return &Response[T,R]{
				StatusCode: responseInstance.StatusCode(),
			},parseErr
		}

		return &Response[T, R]{
			StatusCode: responseInstance.StatusCode(),
			Error:      responseBody,
		}, nil
	}

	responseBody, parseErr := parseResponse[T](responseInstance.Body(), responseInstance.RawResponse)
	if parseErr != nil {
			return &Response[T,R]{
				StatusCode: responseInstance.StatusCode(),
			},parseErr
	}

	return &Response[T, R]{
		StatusCode: responseInstance.StatusCode(),
		Body:       responseBody,
	}, nil
}
