package handlers

import (
	"io"
	"net/http"
	"solacenet-gateway/config"

	"github.com/gin-gonic/gin"
)

// ProxyHandler proxies requests to backend services
func ProxyHandler(cfg *config.Config) gin.HandlerFunc {
	return func(c *gin.Context) {
		// Build backend URL
		backendURL := cfg.BackendURL + c.Request.URL.Path
		if c.Request.URL.RawQuery != "" {
			backendURL += "?" + c.Request.URL.RawQuery
		}

		// Create request
		req, err := http.NewRequest(c.Request.Method, backendURL, c.Request.Body)
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"error": "Failed to create request",
			})
			return
		}

		// Copy headers
		for key, values := range c.Request.Header {
			for _, value := range values {
				req.Header.Add(key, value)
			}
		}

		// Make request
		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			c.JSON(http.StatusBadGateway, gin.H{
				"error": "Failed to reach backend",
			})
			return
		}
		defer resp.Body.Close()

		// Copy response headers
		for key, values := range resp.Header {
			for _, value := range values {
				c.Header(key, value)
			}
		}

		// Copy response body
		c.Status(resp.StatusCode)
		io.Copy(c.Writer, resp.Body)
	}
}
