package routes

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

func GetProductNewSecondColorsHandler(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
	}

	rows, err := db.MssqlDB.Query(
		queries.GetProductNewSecondColors,
		sql.Named("ProductCode", code),
		sql.Named("ColorCode", color),
	)
	if err != nil {
		http.Error(w, "Yeni urun 2. renk listesi alinamadi: "+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("Satir okunamadi:", err)
			continue
		}
		list = append(list, c)
	}

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