package routes

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

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

	itemTypeCode := int16(1)
	if raw := r.URL.Query().Get("itemTypeCode"); raw != "" {
		v, err := strconv.Atoi(raw)
		if err != nil || v <= 0 {
			http.Error(w, "itemTypeCode gecersiz", http.StatusBadRequest)
			return
		}
		itemTypeCode = int16(v)
	}

	rows, err := db.MssqlDB.Query(queries.GetProductAttributes, itemTypeCode)
	if err != nil {
		http.Error(w, "Product attributes alinamadi: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	list := make([]models.ProductAttributeOption, 0, 256)
	for rows.Next() {
		var x models.ProductAttributeOption
		if err := rows.Scan(
			&x.ItemTypeCode,
			&x.AttributeTypeCode,
			&x.AttributeTypeDescription,
			&x.AttributeCode,
			&x.AttributeDescription,
		); err != nil {
			continue
		}
		list = append(list, x)
	}

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