package middleware

import (
	"fmt"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// TTL_LEGACY_ROUTES defines the time-to-live for legacy routes before they are removed.
const TTL_LEGACY_ROUTES = 30 * 24 * time.Hour // 30 days

// DeprecationWarning returns a Gin middleware that adds a "Deprecated" header
// and logs a warning for requests to legacy routes.
func DeprecationWarning(logger *zap.Logger) gin.HandlerFunc {
	// Calculate the deprecation date once when the middleware is initialized
	deprecationDate := time.Now().Add(TTL_LEGACY_ROUTES).Format(time.RFC1123)

	return func(c *gin.Context) {
		// Log a warning for each access to a deprecated route
		logger.Warn(
			"Access to deprecated route",
			zap.String("method", c.Request.Method),
			zap.String("path", c.Request.URL.Path),
			zap.String("deprecation_date", deprecationDate),
			zap.String("action", "Please update your client to use the /api/v1/* equivalent."),
		)

		// Add the Deprecated header
		c.Header("Deprecated", fmt.Sprintf("true; sunset=%s; link=https://www.veza.app/api/v1/migration-guide", deprecationDate))
		c.Next()
	}
}
