package middleware

import (
	"net/http"

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

	"github.com/RyanCopley/skybridge/user/internal/config"
)

// Authentication middleware
func Authentication(cfg config.ConfigProvider, logger *zap.Logger) gin.HandlerFunc {
	return gin.HandlerFunc(func(c *gin.Context) {
		// For development, we'll use header-based authentication
		if cfg.GetString("AUTH_PROVIDER") == "header" {
			userEmail := c.GetHeader(cfg.GetString("AUTH_HEADER_USER_EMAIL"))
			if userEmail == "" {
				logger.Warn("Missing authentication header",
					zap.String("header", cfg.GetString("AUTH_HEADER_USER_EMAIL")),
					zap.String("path", c.Request.URL.Path))
				
				c.JSON(http.StatusUnauthorized, gin.H{
					"error": "Authentication required",
				})
				c.Abort()
				return
			}

			// Set actor in context for handlers
			c.Set("actor_id", userEmail)
			c.Set("user_email", userEmail)
		}

		c.Next()
	})
}