package infra

import (
	"fmt"
	"net/http"
	"time"
)

// HealthCheckHTTP hace polling HTTP GET a url hasta recibir status 200
// o hasta que pasen timeoutSecs segundos. Entre intentos espera intervalMs milisegundos.
func HealthCheckHTTP(url string, timeoutSecs, intervalMs int) error {
	deadline := time.Now().Add(time.Duration(timeoutSecs) * time.Second)
	interval := time.Duration(intervalMs) * time.Millisecond

	client := &http.Client{
		Timeout: time.Duration(intervalMs)*time.Millisecond + 500*time.Millisecond,
	}

	var lastErr error
	for time.Now().Before(deadline) {
		resp, err := client.Get(url)
		if err == nil {
			resp.Body.Close()
			if resp.StatusCode == http.StatusOK {
				return nil
			}
			lastErr = fmt.Errorf("status %d", resp.StatusCode)
		} else {
			lastErr = err
		}
		time.Sleep(interval)
	}

	if lastErr != nil {
		return fmt.Errorf("health check %s timeout after %ds: %w", url, timeoutSecs, lastErr)
	}
	return fmt.Errorf("health check %s timeout after %ds", url, timeoutSecs)
}
