package middlewares

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

func AuthMiddleware(db *sql.DB, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		authHeader := r.Header.Get("Authorization")
		if authHeader == "" {
			log.Printf(
				"AUTH_MIDDLEWARE 401 reason=missing_authorization_header method=%s path=%s",
				r.Method,
				r.URL.Path,
			)
			http.Error(w, "unauthorized: authorization header missing", http.StatusUnauthorized)
			return
		}

		parts := strings.SplitN(authHeader, " ", 2)
		if len(parts) != 2 || parts[0] != "Bearer" {
			log.Printf(
				"AUTH_MIDDLEWARE 401 reason=invalid_authorization_format method=%s path=%s raw=%q",
				r.Method,
				r.URL.Path,
				authHeader,
			)
			http.Error(w, "unauthorized: invalid authorization format", http.StatusUnauthorized)
			return
		}

		claims, err := auth.ValidateToken(parts[1])
		if err != nil {
			log.Printf(
				"AUTH_MIDDLEWARE 401 reason=token_validation_failed method=%s path=%s err=%v",
				r.Method,
				r.URL.Path,
				err,
			)
			http.Error(w, "unauthorized: token validation failed", http.StatusUnauthorized)
			return
		}

		ctx := auth.WithClaims(r.Context(), claims)
		log.Printf(
			"AUTH_MIDDLEWARE PASS user=%d role=%s method=%s path=%s",
			claims.ID,
			claims.RoleCode,
			r.Method,
			r.URL.Path,
		)

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