package middleware

import (
	"context"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/pkg/apiversion"
	"github.com/perfect-panel/server/pkg/constant"
)

func ApiVersionMiddleware(_ *svc.ServiceContext) func(c *gin.Context) {
	return func(c *gin.Context) {
		rawVersion := strings.TrimSpace(c.GetHeader("api-header"))
		useLatest := apiversion.UseLatest(rawVersion, apiversion.DefaultThreshold)
		hasAppId := strings.TrimSpace(c.GetHeader("X-App-Id")) != ""

		ctx := context.WithValue(c.Request.Context(), constant.CtxKeyAPIVersionUseLatest, useLatest)
		ctx = context.WithValue(ctx, constant.CtxKeyAPIHeaderRaw, rawVersion)
		ctx = context.WithValue(ctx, constant.CtxKeyHasAppId, hasAppId)
		c.Request = c.Request.WithContext(ctx)

		c.Set("api_header", rawVersion)
		c.Next()
	}
}
