package routes

import (
	"bssapp-backend/auth"
	"bssapp-backend/internal/i18n"
	"bssapp-backend/models"
	"bssapp-backend/queries"
	"encoding/json"
	"net/http"
	"strconv"
)

// GET /api/statements
func GetStatementHeadersHandler(w http.ResponseWriter, r *http.Request) {

	claims, ok := auth.GetClaimsFromContext(r.Context())
	if !ok || claims == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

	params := models.StatementParams{
		StartDate:      r.URL.Query().Get("startdate"),
		EndDate:        r.URL.Query().Get("enddate"),
		AccountCode:    r.URL.Query().Get("accountcode"),
		LangCode:       i18n.ResolveLangCode(r.URL.Query().Get("langcode"), r.Header.Get("Accept-Language")),
		Parislemler:    r.URL.Query()["parislemler"],
		ExcludeOpening: false,
	}
	if raw := r.URL.Query().Get("excludeopening"); raw != "" {
		if parsed, err := strconv.ParseBool(raw); err == nil {
			params.ExcludeOpening = parsed
		}
	}

	statements, err := queries.GetStatements(r.Context(), params)
	if err != nil {
		http.Error(w, "Error fetching statements: "+err.Error(), http.StatusInternalServerError)
		return
	}

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