package routes

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

// GET /api/pricing/production-product-costing/last10-warnings?n_onml_no=100001
func GetProductionProductCostingLast10WarningsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	pg := db.PgDB
	if pg == nil {
		http.Error(w, "Postgres baglantisi aktif degil", http.StatusServiceUnavailable)
		return
	}
	if err := queries.EnsureProductionCostingLast10WarningTables(pg); err != nil {
		http.Error(w, "warning table bootstrap error", http.StatusInternalServerError)
		return
	}

	nStr := strings.TrimSpace(r.URL.Query().Get("n_onml_no"))
	n, _ := strconv.Atoi(nStr)
	if n <= 0 {
		http.Error(w, "n_onml_no zorunlu", http.StatusBadRequest)
		return
	}

	traceID := utils.TraceIDFromRequest(r)
	ctx := utils.ContextWithTraceID(r.Context(), traceID)

	list, err := queries.ListProductionCostingLast10WarningsByOnMLNo(ctx, pg, n)
	if err != nil {
		http.Error(w, "Veritabani hatasi", http.StatusInternalServerError)
		return
	}
	_ = json.NewEncoder(w).Encode(map[string]any{
		"n_onml_no": n,
		"count":     len(list),
		"items":     list,
	})
}
