package middlewares

import (
	"bssapp-backend/auth"
	"log"
	"net/http"
	"strings"
)

var publicPaths = []string{
	"/api/auth/login",
	"/api/auth/refresh",
	"/api/password/forgot",
	"/api/password/reset",
	"/api/language/translations/runtime",
	"/api/product-images/",
	"/uploads/",
}

func GlobalAuthMiddleware(db any, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		path := r.URL.Path

		// PUBLIC ROUTES
		for _, p := range publicPaths {
			if strings.HasPrefix(path, p) {
				next.ServeHTTP(w, r)
				return
			}
		}

		// JWT
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		claims, err := auth.ValidateToken(parts[1])
		if err != nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}

		ctx := auth.WithClaims(r.Context(), claims)

		log.Printf("🔐 GLOBAL AUTH user=%d role=%s",
			claims.ID,
			claims.RoleCode,
		)

		next.ServeHTTP(w, r.WithContext(ctx))
	})
}
