package baseadapter

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
)

type Rest struct {
	baseURL     string
	bearerToken string
}

func NewRest(baseURL string, bearerToken string) Rest {
	return Rest{
		baseURL:     baseURL,
		bearerToken: bearerToken,
	}
}

const defaultBodyBufferSize = 100

func (b *Rest) CreateRequest(ctx context.Context, method string, body any, path ...string) (r *http.Request, err error) {
	target, err := url.JoinPath(b.baseURL, path...)
	if err != nil {
		err = fmt.Errorf("can not parse path: %w", err)
		return
	}

	var bodyReader io.Reader
	if body != nil {
		bodyBuff := bytes.NewBuffer(make([]byte, 0, defaultBodyBufferSize))

		err = json.NewEncoder(bodyBuff).Encode(body)
		if err != nil {
			return
		}

		bodyReader = bodyBuff
	}

	req, err := http.NewRequest(method, target, bodyReader)
	if err != nil {
		return nil, err
	}

	req = req.WithContext(ctx)

	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	if b.bearerToken != "" {
		req.Header.Set("Authorization", "Bearer "+b.bearerToken)
	}

	return req, nil
}
