package twitchhttp

import (
	"encoding/json"
	"fmt"
	"net/http"
)

type Error struct {
	Message    string `json:"message"`
	StatusCode int    `json:"-"`
}

func (e *Error) Error() string {
	return fmt.Sprintf("%d: %s", e.StatusCode, e.Message)
}

func HandleFailedResponse(resp *http.Response) *Error {
	httpError := &Error{StatusCode: resp.StatusCode}
	err := json.NewDecoder(resp.Body).Decode(httpError)
	if err != nil {
		httpError.Message = fmt.Sprintf("Unable to read response body: %s", err)
	}

	return httpError
}
