package httpapi

import (
	"net/http"
	"strings"

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

const requestIDContextKey = "requestID"

func requestIDMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		requestID := strings.TrimSpace(c.GetHeader("X-Request-Id"))
		if requestID == "" {
			requestID = uuid.NewString()
		}
		c.Set(requestIDContextKey, requestID)
		c.Header("X-Request-Id", requestID)
		c.Next()
	}
}

func requestIDFromContext(c *gin.Context) string {
	if value, exists := c.Get(requestIDContextKey); exists {
		if requestID, ok := value.(string); ok {
			return requestID
		}
	}
	return ""
}

func (s *Server) writeStatusError(c *gin.Context, status int, message string) {
	code := "internal_error"
	switch status {
	case http.StatusBadRequest:
		code = "bad_request"
	case http.StatusUnauthorized:
		code = "unauthorized"
	case http.StatusForbidden:
		code = "forbidden"
	case http.StatusNotFound:
		code = "not_found"
	case http.StatusConflict:
		code = "conflict"
	case http.StatusBadGateway:
		code = "upstream_error"
	case http.StatusServiceUnavailable:
		code = "service_unavailable"
	}
	if strings.TrimSpace(message) == "" {
		message = http.StatusText(status)
	}
	c.JSON(status, gin.H{
		"error": gin.H{
			"code":      code,
			"message":   message,
			"requestId": requestIDFromContext(c),
		},
	})
}
