package routes

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

func GetProductDetailHandler(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", http.StatusBadRequest)
		return
	}

	row := db.MssqlDB.QueryRow(queries.GetProductDetail, code)

	var p models.ProductDetail
	err := row.Scan(
		&p.ProductCode,
		new(string), // BOS7
		new(string), // ProductDescription
		new(string), // ProductAtt42
		&p.UrunIlkGrubu,
		new(string), // ProductAtt01
		&p.UrunAnaGrubu,
		new(string), // ProductAtt02
		&p.UrunAltGrubu,
		new(string), // ProductAtt41
		&p.UrunIcerik,
		new(string), // ProductAtt10
		new(string), // Marka
		new(string), // ProductAtt11
		&p.Drop,
		new(string), // ProductAtt29
		new(string), // Karisim
		new(string), // ProductAtt45
		&p.AskiliYan,
		new(string), // ProductAtt44
		&p.Kategori,
		new(string), // ProductAtt38
		&p.Fit1,
		new(string), // ProductAtt39
		&p.Fit2,
	)
	if err != nil {
		log.Println("❌ Ürün detayları alınamadı:", err)
		http.Error(w, "Veri okuma hatası: "+err.Error(), http.StatusInternalServerError)
		return
	}

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