package jobqueue

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

// HTTPResult is a result of a http request
type HTTPResult struct {
	StatusCode int
	Body       string
}

type HTTPRunnable struct {
	URL    string
	Method string
	Header map[string]string
	Body   string
}

func (h *HTTPRunnable) Run() (RunResult[HTTPResult], error) {
	client := &http.Client{}

	reqBody := bytes.NewBufferString(h.Body)
	req, err := http.NewRequest(h.Method, h.URL, reqBody)
	if err != nil {
		return RunResult[HTTPResult]{Status: ResultStatusFailed}, err
	}

	for key, value := range h.Header {
		req.Header.Set(key, value)
	}

	resp, err := client.Do(req)
	if err != nil {
		return RunResult[HTTPResult]{Status: ResultStatusFailed}, err
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return RunResult[HTTPResult]{Status: ResultStatusFailed}, err
	}

	return RunResult[HTTPResult]{
		Status: ResultStatusSuccess,
		Data: HTTPResult{
			StatusCode: resp.StatusCode,
			Body:       string(body),
		},
	}, nil
}