package routes

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

type agingCacheRefreshResponse struct {
	OK      bool   `json:"ok"`
	Message string `json:"message"`
}

// POST /api/finance/account-aging-statement/rebuild-cache
// Runs only step2 + step3.
func RebuildStatementAgingCacheHandler(w http.ResponseWriter, r *http.Request) {
	claims, ok := auth.GetClaimsFromContext(r.Context())
	if !ok || claims == nil {
		http.Error(w, "unauthorized", http.StatusUnauthorized)
		return
	}

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

	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	_ = json.NewEncoder(w).Encode(agingCacheRefreshResponse{
		OK:      true,
		Message: "SP_BUILD_CARI_VADE_GUN_STAGING -> SP_BUILD_CARI_BAKIYE_CACHE çalıştırıldı.",
	})
}
