package routes

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

// ======================================================
// 📌 OrderProductionListRoute — Üretime verilecek siparişler
// ======================================================
func OrderProductionListRoute(mssql *sql.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		// --------------------------------------------------
		// 🔍 Query Param (RAW + TRIM)
		// --------------------------------------------------
		raw := r.URL.Query().Get("search")
		search := strings.TrimSpace(raw)

		log.Printf(
			"📥 /api/orders/production-list search raw=%q trimmed=%q lenRaw=%d lenTrim=%d",
			raw,
			search,
			len(raw),
			len(search),
		)

		// --------------------------------------------------
		// 🗄 SQL CALL (WITH CONTEXT)
		// --------------------------------------------------
		rows, err := queries.GetOrderProductionList(
			r.Context(),
			mssql,
			db.PgDB,
			search,
		)

		if err != nil {
			log.Printf("❌ SQL sorgu hatası: %v", err)
			http.Error(w, "Veritabanı hatası", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		// --------------------------------------------------
		// 📦 Sonuç Listesi
		// --------------------------------------------------
		list := make([]models.OrderList, 0, 100)
		count := 0

		// ==================================================
		// 🧠 SCAN — SQL SELECT ile BİRE BİR (18 kolon)
		// ==================================================
		for rows.Next() {

			var o models.OrderList

			err = rows.Scan(
				&o.OrderHeaderID, // 1
				&o.OrderNumber,   // 2
				&o.OrderDate,     // 3

				&o.CurrAccCode,        // 4
				&o.CurrAccDescription, // 5

				&o.MusteriTemsilcisi, // 6
				&o.Piyasa,            // 7

				&o.CreditableConfirmedDate, // 8
				&o.DocCurrencyCode,         // 9

				&o.TotalAmount,    // 10
				&o.TotalAmountUSD, // 11
				&o.PackedAmount,   // 12
				&o.PackedUSD,      // 13
				&o.PackedRatePct,  // 14

				&o.IsCreditableConfirmed, // 15
				&o.HasUretimUrunu,        // 16
				&o.Description,           // 17

				&o.ExchangeRateUSD, // 18
			)

			if err != nil {
				log.Printf(
					"⚠️ SCAN HATASI | OrderHeaderID=%v | err=%v",
					o.OrderHeaderID,
					err,
				)
				continue
			}

			list = append(list, o)
			count++
		}

		if err := rows.Err(); err != nil {
			log.Printf("⚠️ rows.Err(): %v", err)
		}

		// --------------------------------------------------
		// 📊 RESULT LOG
		// --------------------------------------------------
		claims, _ := auth.GetClaimsFromContext(r.Context())

		log.Printf(
			"✅ Order production list DONE | user=%d | search=%q | resultCount=%d",
			claims.ID,
			search,
			count,
		)

		// --------------------------------------------------
		// ✅ JSON RESPONSE
		// --------------------------------------------------
		if err := json.NewEncoder(w).Encode(list); err != nil {
			log.Printf("❌ encode error: %v", err)
		}
	})
}
