package routes

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

// GET /api/finance/customer-balances
func GetCustomerBalanceListHandler(w http.ResponseWriter, r *http.Request) {
	claims, ok := auth.GetClaimsFromContext(r.Context())
	if !ok || claims == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	selectedDate := strings.TrimSpace(r.URL.Query().Get("selected_date"))
	if selectedDate == "" {
		selectedDate = time.Now().Format("2006-01-02")
	}

	params := models.CustomerBalanceListParams{
		SelectedDate: selectedDate,
		CariSearch:   strings.TrimSpace(r.URL.Query().Get("cari_search")),
		CariIlkGrup:  strings.TrimSpace(r.URL.Query().Get("cari_ilk_grup")),
		Piyasa:       strings.TrimSpace(r.URL.Query().Get("piyasa")),
		Temsilci:     strings.TrimSpace(r.URL.Query().Get("temsilci")),
		RiskDurumu:   strings.TrimSpace(r.URL.Query().Get("risk_durumu")),
		IslemTipi:    strings.TrimSpace(r.URL.Query().Get("islem_tipi")),
		Ulke:         strings.TrimSpace(r.URL.Query().Get("ulke")),
		Il:           strings.TrimSpace(r.URL.Query().Get("il")),
		Ilce:         strings.TrimSpace(r.URL.Query().Get("ilce")),
	}

	rows, err := queries.GetCustomerBalanceList(r.Context(), params)
	if err != nil {
		log.Println("GetCustomerBalanceList error:", err)
		http.Error(w, "db error: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(rows); err != nil {
		log.Println("GetCustomerBalanceList json encode error:", err)
	}
}
