package routes

import (
	"bssapp-backend/db"
	"bssapp-backend/queries"
	"context"
	"encoding/json"
	"log"
	"net/http"
	"strconv"
	"strings"
	"time"
)

// GetProductStockQueryHandler
// GET /api/product-stock-query?code=...
func GetProductStockQueryHandler(w http.ResponseWriter, r *http.Request) {
	code := strings.TrimSpace(r.URL.Query().Get("code"))
	if code == "" {
		http.Error(w, "Eksik parametre: code gerekli", http.StatusBadRequest)
		return
	}

	ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
	defer cancel()

	rows, err := db.MssqlDB.QueryContext(ctx, queries.GetProductStockQuery, code)
	if err != nil {
		log.Printf("❌ [PRODUCT-STOCK-QUERY] SQL hatası: %v", err)
		http.Error(w, "SQL hatası: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	columns, err := rows.Columns()
	if err != nil {
		http.Error(w, "Kolon bilgisi alınamadı", http.StatusInternalServerError)
		return
	}

	result := make([]map[string]interface{}, 0, 128)
	for rows.Next() {
		raw := make([]interface{}, len(columns))
		dest := make([]interface{}, len(columns))
		for i := range raw {
			dest[i] = &raw[i]
		}
		if err := rows.Scan(dest...); err != nil {
			log.Printf("⚠️ [PRODUCT-STOCK-QUERY] scan hatası: %v", err)
			continue
		}

		rowMap := make(map[string]interface{}, len(columns))
		for i, c := range columns {
			rowMap[c] = normalizeSQLValue(raw[i])
		}
		result = append(result, rowMap)
	}

	if err := rows.Err(); err != nil {
		http.Error(w, "Satır okuma hatası: "+err.Error(), http.StatusInternalServerError)
		return
	}

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

func normalizeSQLValue(v interface{}) interface{} {
	switch val := v.(type) {
	case nil:
		return ""
	case []byte:
		s := strings.TrimSpace(string(val))
		if s == "" {
			return ""
		}
		if n, err := strconv.ParseFloat(strings.ReplaceAll(s, ",", "."), 64); err == nil {
			return n
		}
		return s
	default:
		return val
	}
}
