package routes

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

// GET /api/finance/account-aging-statement
func GetStatementAgingHandler(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("enddate"))
	if selectedDate == "" {
		selectedDate = strings.TrimSpace(r.URL.Query().Get("selected_date"))
	}
	if selectedDate == "" {
		selectedDate = time.Now().Format("2006-01-02")
	}
	params := models.StatementAgingParams{
		AccountCode: strings.TrimSpace(r.URL.Query().Get("accountcode")),
		EndDate:     selectedDate,
		Parislemler: r.URL.Query()["parislemler"],
	}

	if err := queries.RebuildStatementAgingCache(r.Context()); err != nil {
		http.Error(w, "Error rebuilding aging cache: "+err.Error(), http.StatusInternalServerError)
		return
	}

	rows, err := queries.GetStatementAging(params)
	if err != nil {
		http.Error(w, "Error fetching aging statement: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(rows); err != nil {
		http.Error(w, "Error encoding response: "+err.Error(), http.StatusInternalServerError)
	}
}

// GET /api/finance/aged-customer-balance-list
func GetAgedCustomerBalanceListHandler(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("enddate"))
	if selectedDate == "" {
		selectedDate = strings.TrimSpace(r.URL.Query().Get("selected_date"))
	}
	if selectedDate == "" {
		selectedDate = time.Now().Format("2006-01-02")
	}
	params := models.StatementAgingParams{
		AccountCode: strings.TrimSpace(r.URL.Query().Get("accountcode")),
		EndDate:     selectedDate,
		Parislemler: r.URL.Query()["parislemler"],
	}

	listParams := 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")),
	}
	if params.AccountCode != "" {
		listParams.CariSearch = params.AccountCode
	}

	if err := queries.RebuildStatementAgingCache(r.Context()); err != nil {
		http.Error(w, "Error rebuilding aging cache: "+err.Error(), http.StatusInternalServerError)
		return
	}

	rows, err := queries.GetStatementAgingBalanceList(r.Context(), listParams)
	if err != nil {
		http.Error(w, "Error fetching aging statement: "+err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	if err := json.NewEncoder(w).Encode(rows); err != nil {
		http.Error(w, "Error encoding response: "+err.Error(), http.StatusInternalServerError)
	}
}
