package infra

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

// HTTPServe arranca un servidor HTTP en addr y realiza graceful shutdown cuando ctx se cancela.
// Espera hasta 30 segundos para que las conexiones activas cierren antes de forzar el shutdown.
func HTTPServe(addr string, handler http.Handler, ctx context.Context) error {
	srv := &http.Server{
		Addr:    addr,
		Handler: handler,
	}

	errCh := make(chan error, 1)
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			errCh <- fmt.Errorf("http serve %s: %w", addr, err)
		}
		close(errCh)
	}()

	select {
	case err := <-errCh:
		return err
	case <-ctx.Done():
		shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
		defer cancel()
		if err := srv.Shutdown(shutdownCtx); err != nil {
			return fmt.Errorf("http shutdown %s: %w", addr, err)
		}
		return nil
	}
}
