package routes

import (
	"bssapp-backend/auth"
	"bssapp-backend/db"
	"bssapp-backend/models"
	"bssapp-backend/queries"
	"encoding/json"
	"log"
	"net/http"
)

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

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

	code := r.URL.Query().Get("code")
	if code == "" {
		http.Error(w, "Eksik parametre: code gerekli", http.StatusBadRequest)
		return
	}

	rows, err := db.MssqlDB.Query(queries.GetProductColors, code)
	if err != nil {
		http.Error(w, "Renk listesi alınamadı: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var list []models.ProductColor
	for rows.Next() {
		var c models.ProductColor
		if err := rows.Scan(&c.ProductCode, &c.ColorCode, &c.ColorDescription); err != nil {
			log.Println("Satır okunamadı:", err)
			continue
		}
		list = append(list, c)
	}

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

	log.Printf("✅ [1.COLOR] %s -> %d kayıt", code, len(list))
}
