package routes

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

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

	query := `
SELECT 
    ItemTypeCode, 
    ItemCode, 
    ItemDimTypeCode, 
    ProductTypeCode, 
    ProductHierarchyID,
    UnitOfMeasureCode1, 
    ItemAccountGrCode, 
    ItemTaxGrCode, 
    ItemPaymentPlanGrCode, 
    ItemDiscountGrCode, 
    ItemVendorGrCode,
    PromotionGroupCode, 
    ProductCollectionGrCode, 
    StorePriceLevelCode, 
    PerceptionOfFashionCode,
    CommercialRoleCode, 
    StoreCapacityLevelCode, 
    CustomsTariffNumberCode, 
    CompanyCode
FROM dbo.cdItem
WHERE ItemCode = @p1;
`
	row := db.MssqlDB.QueryRow(query, code)

	var p models.OrderProductionCdItemDraft
	err := row.Scan(
		&p.ItemTypeCode,
		&p.ItemCode,
		&p.ItemDimTypeCode,
		&p.ProductTypeCode,
		&p.ProductHierarchyID,
		&p.UnitOfMeasureCode1,
		&p.ItemAccountGrCode,
		&p.ItemTaxGrCode,
		&p.ItemPaymentPlanGrCode,
		&p.ItemDiscountGrCode,
		&p.ItemVendorGrCode,
		&p.PromotionGroupCode,
		&p.ProductCollectionGrCode,
		&p.StorePriceLevelCode,
		&p.PerceptionOfFashionCode,
		&p.CommercialRoleCode,
		&p.StoreCapacityLevelCode,
		&p.CustomsTariffNumberCode,
		&p.CompanyCode,
	)
	if err != nil {
		if err.Error() == "sql: no rows in result set" {
			http.Error(w, "Ürün bulunamadı", http.StatusNotFound)
			return
		}
		log.Printf("[GetProductCdItem] error code=%s err=%v", code, err)
		http.Error(w, "Ürün cdItem bilgisi alınamadı", http.StatusInternalServerError)
		return
	}

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