package routes

import (
	"bssapp-backend/auth"
	"bssapp-backend/internal/authz"
	"bssapp-backend/queries"
	"encoding/json"
	"log"
	"net/http"
)

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

	// ✅ AUTH (sadece login kontrolü)
	claims, ok := auth.GetClaimsFromContext(r.Context())
	if !ok || claims == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	// ✅ DEBUG (scope kontrol için faydalı)
	log.Println("🔍 PIYASA CTX:", authz.GetPiyasaCodesFromCtx(r.Context()))

	// ✅ QUERY
	accounts, err := queries.GetAccounts(r.Context())
	if err != nil {
		log.Println("❌ GetAccounts error:", err)
		http.Error(w, "db error", http.StatusInternalServerError)
		return
	}

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

	if err := json.NewEncoder(w).Encode(accounts); err != nil {
		log.Println("❌ JSON encode error:", err)
		return
	}
}
