package middlewares

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

// 🔓 force_password_change=true iken izinli endpoint prefixleri
var passwordChangeAllowlist = []string{
	"/api/password/change",
	"/api/password/reset",
	"/api/password/reset/validate",
	"/api/auth/refresh",
}

func ForcePasswordChangeGuard(db *sql.DB) func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

			claims, ok := auth.GetClaimsFromContext(r.Context())
			if !ok || claims == nil {
				log.Println("❌ FPC GUARD: claims NOT FOUND")
				http.Error(w, "Unauthorized", http.StatusUnauthorized)
				return
			}

			log.Printf(
				"🛡️ FPC GUARD user=%s force=%v path=%s",
				claims.Username,
				claims.ForcePasswordChange,
				r.URL.Path,
			)

			// 🔓 Şifre değişimi zorunlu DEĞİL → serbest
			if !claims.ForcePasswordChange {
				next.ServeHTTP(w, r)
				return
			}

			// 🔐 Şifre değişimi ZORUNLU → allowlist kontrolü
			for _, allowed := range passwordChangeAllowlist {
				if strings.HasPrefix(r.URL.Path, allowed) {
					log.Printf(
						"✅ FPC GUARD PASS user=%s path=%s",
						claims.Username,
						r.URL.Path,
					)
					next.ServeHTTP(w, r)
					return
				}
			}

			// ⛔ Zorunlu ama yanlış endpoint
			log.Printf(
				"⛔ FPC GUARD BLOCK user=%s path=%s",
				claims.Username,
				r.URL.Path,
			)

			http.Error(w, "password change required", http.StatusUnauthorized)
		})
	}
}
