package routes

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

type bulkCloseOrdersRequest struct {
	OrderNumbers []string `json:"order_numbers"`
}

func OrderCloseReadyListRoute(mssqlDB *sql.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		raw := r.URL.Query().Get("search")
		search := strings.TrimSpace(raw)

		rows, err := queries.GetOrderListCloseReady(
			r.Context(),
			mssqlDB,
			db.PgDB,
			search,
		)
		if err != nil {
			log.Printf("❌ close-ready list query error: %v", err)
			http.Error(w, "Veritabanı hatası", http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		list := make([]models.OrderList, 0, 100)
		for rows.Next() {
			var o models.OrderList
			if err := rows.Scan(
				&o.OrderHeaderID,
				&o.OrderNumber,
				&o.OrderDate,
				&o.CurrAccCode,
				&o.CurrAccDescription,
				&o.MusteriTemsilcisi,
				&o.Piyasa,
				&o.CreditableConfirmedDate,
				&o.DocCurrencyCode,
				&o.TotalAmount,
				&o.TotalAmountUSD,
				&o.PackedAmount,
				&o.PackedUSD,
				&o.PackedRatePct,
				&o.IsCreditableConfirmed,
				&o.Description,
				&o.ExchangeRateUSD,
			); err != nil {
				log.Printf("⚠️ close-ready scan error: %v", err)
				continue
			}
			list = append(list, o)
		}

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

		_ = json.NewEncoder(w).Encode(list)
	})
}

func OrderBulkCloseRoute(mssqlDB *sql.DB) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")

		var req bulkCloseOrdersRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, "Geçersiz JSON", http.StatusBadRequest)
			return
		}

		if len(req.OrderNumbers) == 0 {
			http.Error(w, "order_numbers zorunludur", http.StatusBadRequest)
			return
		}

		updatedBy := "SYSTEM"
		if claims, ok := auth.GetClaimsFromContext(r.Context()); ok && claims != nil {
			if u := strings.TrimSpace(claims.Username); u != "" {
				updatedBy = u
			}
		}

		affected, err := queries.BulkCloseOrders(
			r.Context(),
			mssqlDB,
			db.PgDB,
			req.OrderNumbers,
			updatedBy,
		)
		if err != nil {
			log.Printf("❌ bulk close failed: %v", err)
			http.Error(w, "Toplu kapatma sırasında hata oluştu", http.StatusInternalServerError)
			return
		}

		_ = json.NewEncoder(w).Encode(map[string]any{
			"success":  true,
			"affected": affected,
		})
	})
}
