package infra

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

// HttpGetJSON realiza un GET request a url y parsea la respuesta como JSON.
// Agrega Accept: application/json automaticamente. Retorna error si status >= 400
// incluyendo el status code y los primeros 200 bytes del body.
func HttpGetJSON(url string, headers map[string]string, timeout time.Duration) (map[string]any, error) {
	client := &http.Client{Timeout: timeout}

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return nil, fmt.Errorf("http_get_json: build request: %w", err)
	}

	req.Header.Set("Accept", "application/json")
	for k, v := range headers {
		req.Header.Set(k, v)
	}

	resp, err := client.Do(req)
	if err != nil {
		return nil, fmt.Errorf("http_get_json: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("http_get_json: read body: %w", err)
	}

	if resp.StatusCode >= 400 {
		preview := body
		if len(preview) > 200 {
			preview = preview[:200]
		}
		shortURL := url
		if len(shortURL) > 100 {
			shortURL = shortURL[:100]
		}
		return nil, fmt.Errorf("http_get_json: HTTP %d at %q — %s", resp.StatusCode, shortURL, preview)
	}

	var result map[string]any
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, fmt.Errorf("http_get_json: parse JSON: %w", err)
	}

	return result, nil
}
