package routes

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

// ✅ GET /api/product-secondcolor?code=S001-DCY18144&color=001
func GetProductSecondColorsHandler(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")
	color := r.URL.Query().Get("color")

	if code == "" || color == "" {
		http.Error(w, "Eksik parametre: code ve color gerekli", http.StatusBadRequest)
		return
	}

	log.Printf("🎨 [2.COLOR] İstek alındı -> code=%s color=%s", code, color)

	rows, err := db.MssqlDB.Query(
		queries.GetProductSecondColors,
		sql.Named("ProductCode", code),
		sql.Named("ColorCode", color),
	)
	if err != nil {
		log.Println("❌ DB sorgu hatası:", err)
		http.Error(w, "2. renk listesi alınamadı: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

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

	if err := rows.Err(); err != nil {
		log.Println("⚠️ Row iteration hatası:", err)
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(list); err != nil {
		log.Println("❌ JSON encode hatası:", err)
		http.Error(w, "JSON encode başarısız", http.StatusInternalServerError)
		return
	}

	log.Printf("✅ [2.COLOR] %s / %s -> %d kayıt döndü", code, color, len(list))
}
