package middleware

import (
	"net/http"

	"github.com/labstack/echo/v4"

	"github.com/treytartt/honeydue-api/internal/dto/responses"
)

// HostCheck returns middleware that validates the request Host header against
// a set of allowed hosts. This prevents SSRF attacks where an attacker crafts
// a request with an arbitrary Host header to reach internal services via the
// reverse proxy.
//
// If allowedHosts is empty the middleware is a no-op (all hosts pass).
func HostCheck(allowedHosts []string) echo.MiddlewareFunc {
	allowed := make(map[string]struct{}, len(allowedHosts))
	for _, h := range allowedHosts {
		allowed[h] = struct{}{}
	}

	return func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			// If no allowed hosts configured, skip the check
			if len(allowed) == 0 {
				return next(c)
			}

			host := c.Request().Host
			if _, ok := allowed[host]; !ok {
				return c.JSON(http.StatusForbidden, responses.ErrorResponse{
					Error: "Forbidden",
				})
			}

			return next(c)
		}
	}
}
