package client

import (
	"bytes"
	"fmt"
	"net/http"

	"penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/json"
)

func parseResponse[T any](body []byte, response *http.Response) (*T, error) {
	isJSONResponse := response.Header.Get("Content-Type") == "application/json"
	fmt.Println("1OOOO", response.Header.Get("Content-Type"), string(body))

	if !isJSONResponse {
		responseBody, unmarshalErr := json.Unmarshal[T](body)
		if unmarshalErr != nil {
			return nil, unmarshalErr
		}

		return responseBody, nil
	}

	responseBody, parseErr := json.Parse[T](bytes.NewReader(body))
	if parseErr != nil {
		return nil, parseErr
	}

	return responseBody, nil
}
