package routes

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

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

	// 🔹 Model kodu zorunlu, renk opsiyonel
	if code == "" {
		http.Error(w, "Eksik parametre: code gerekli", http.StatusBadRequest)
		return
	}

	// 🔧 Eksik parametreleri normalize et
	if color == "" {
		color = " "
	}
	if color2 == "" {
		color2 = " "
	}

	log.Printf("🎨 [COLORSIZE] İstek alındı -> code=%q | color=%q | color2=%q", code, color, color2)

	// ✅ MSSQL’e sıralı 3 parametre gönder (adlı değil!)
	rows, err := db.MssqlDB.Query(queries.GetProductColorSizes, code, color, color2)
	if err != nil {
		log.Printf("❌ [COLORSIZE] DB sorgu hatası: %v", err)
		http.Error(w, "SQL hatası: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	var list []models.ProductColorSize
	for rows.Next() {
		var s models.ProductColorSize
		if err := rows.Scan(&s.ProductCode, &s.ColorCode, &s.ItemDim1Code, &s.ItemDim2Code); err != nil {
			log.Printf("⚠️ [COLORSIZE] Satır okunamadı: %v", err)
			continue
		}
		list = append(list, s)
	}

	if err := rows.Err(); err != nil {
		log.Printf("⚠️ [COLORSIZE] Row iteration hatası: %v", err)
	}

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

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