package routes

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

func GetProductAttributesHandler(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	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)
	}
	log.Printf("[GetProductAttributes] start user=%s itemTypeCode=%d", claims.Username, itemTypeCode)

	rows, err := db.MssqlDB.Query(queries.GetProductAttributes, itemTypeCode)
	if err != nil {
		log.Printf("[GetProductAttributes] query_error user=%s itemTypeCode=%d err=%v duration_ms=%d",
			claims.Username, itemTypeCode, err, time.Since(start).Milliseconds())
		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)
	}
	if err := rows.Err(); err != nil {
		log.Printf("[GetProductAttributes] rows_error user=%s itemTypeCode=%d err=%v duration_ms=%d",
			claims.Username, itemTypeCode, err, time.Since(start).Milliseconds())
		http.Error(w, "Product attributes okunamadi: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_ = json.NewEncoder(w).Encode(list)
	log.Printf("[GetProductAttributes] done user=%s itemTypeCode=%d count=%d duration_ms=%d",
		claims.Username, itemTypeCode, len(list), time.Since(start).Milliseconds())
}

func GetProductItemAttributesHandler(w http.ResponseWriter, r *http.Request) {
	start := time.Now()
	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)
	}

	itemCode := strings.TrimSpace(r.URL.Query().Get("itemCode"))
	if itemCode == "" {
		http.Error(w, "itemCode zorunlu", http.StatusBadRequest)
		return
	}
	log.Printf("[GetProductItemAttributes] start user=%s itemTypeCode=%d itemCode=%s", claims.Username, itemTypeCode, itemCode)

	rows, err := db.MssqlDB.Query(queries.GetProductItemAttributes, itemTypeCode, itemCode)
	if err != nil {
		log.Printf("[GetProductItemAttributes] query_error user=%s itemTypeCode=%d itemCode=%s err=%v duration_ms=%d",
			claims.Username, itemTypeCode, itemCode, err, time.Since(start).Milliseconds())
		http.Error(w, "Product item attributes alinamadi: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	list := make([]models.ProductItemAttributeValue, 0, 64)
	for rows.Next() {
		var x models.ProductItemAttributeValue
		if err := rows.Scan(
			&x.ItemTypeCode,
			&x.AttributeTypeCode,
			&x.AttributeCode,
		); err != nil {
			continue
		}
		list = append(list, x)
	}
	if err := rows.Err(); err != nil {
		log.Printf("[GetProductItemAttributes] rows_error user=%s itemTypeCode=%d itemCode=%s err=%v duration_ms=%d",
			claims.Username, itemTypeCode, itemCode, err, time.Since(start).Milliseconds())
		http.Error(w, "Product item attributes okunamadi: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_ = json.NewEncoder(w).Encode(list)
	log.Printf("[GetProductItemAttributes] done user=%s itemTypeCode=%d itemCode=%s count=%d duration_ms=%d",
		claims.Username, itemTypeCode, itemCode, len(list), time.Since(start).Milliseconds())
}
