package routes

import (
	"encoding/json"
	"log"
	"net/http"

	"bssapp-backend/auth"
	"bssapp-backend/queries"
)

func GetCustomerListHandler(w http.ResponseWriter, r *http.Request) {

	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	// --------------------------------------------------
	// 🔐 CLAIMS (DEBUG / TRACE)
	// --------------------------------------------------
	claims, ok := auth.GetClaimsFromContext(r.Context())
	if !ok || claims == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	log.Printf(
		"📥 /api/customers | user=%d admin=%v",
		claims.ID,
		claims.IsAdmin(),
	)

	// --------------------------------------------------
	// 🗄️ QUERY (CONTEXT TAŞIYOR)
	// --------------------------------------------------
	list, err := queries.GetCustomerList(r.Context())
	if err != nil {
		log.Println("❌ Customer list error:", err)
		http.Error(w, "Veritabanı hatası", http.StatusInternalServerError)
		return
	}

	// --------------------------------------------------
	// 📤 JSON OUTPUT
	// --------------------------------------------------
	if err := json.NewEncoder(w).Encode(list); err != nil {
		log.Printf("❌ JSON encode error: %v", err)
		return
	}

	// --------------------------------------------------
	// 📊 RESULT LOG
	// --------------------------------------------------
	log.Printf(
		"✅ Customer list DONE | user=%d | resultCount=%d",
		claims.ID,
		len(list),
	)
}
