package request

import (
	"encoding/json"
	"errors"

	"github.com/gofiber/fiber/v2"
	"github.com/rs/zerolog/log"
)

func Request(requestMethod string, url string, body any) error {
	a := fiber.AcquireAgent()

	req := a.Request()
	req.Header.SetMethod(requestMethod)

	addr := "http://" + url

	req.SetRequestURI(addr)
	req.Header.SetContentType("application/json")

	reqestBodyBytes, err := json.Marshal(body)

	if err != nil {
		log.Error().Msgf("Failed to marshal request body, err: %s", err)
		return err
	}

	req.SetBody(reqestBodyBytes)

	if err := a.Parse(); err != nil {
		log.Error().Msgf("Failed to parse request, err: %s", err)
		return err
	}

	code, _, errB := a.Bytes()

	if len(errB) != 0 {
		log.Error().Msgf("Failed to parse bytes %v", errB)
		return errB[0]
	}

	if code != 200 {
		log.Error().Msgf("Request failed with code %v", code)
		return errors.New("request failed")
	}

	return nil
}
