package routes

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

// ======================================================
// 📌 OrderListRoute — Sipariş Listeleme API (AUTHZ + SAFE)
// ======================================================
func OrderListRoute(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/list search raw=%q trimmed=%q lenRaw=%d lenTrim=%d",
			raw,
			search,
			len(raw),
			len(search),
		)

		// --------------------------------------------------
		// 🗄️ SQL CALL (WITH CONTEXT)
		// --------------------------------------------------
		rows, err := queries.GetOrderList(
			r.Context(),
			mssql,
			db.PgDB, // ✅ artık var
			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.TerminTarihi,  // 4

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

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

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

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

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

				&o.ExchangeRateUSD, // 19
			)

			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 list DONE | user=%d | search=%q | resultCount=%d",
			claims.ID,
			search,
			count,
		)

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