// Package rest — admin endpoint that forces the running process to reload
// its autonumber metadata snapshot from _System_Field.
//
// Round-6 R5-H1 (HIGH): AutoNumberMetadata is a per-process cache. When
// `cmd/setup apply` writes new AutoNumberFormat / TokenRefs rows on behalf
// of a pack, the setup CLI lives in a separate process from the running
// backend pods — so the pods keep serving stale TokenRefs until they
// restart. The safest generic fix is a runbook that triggers a rolling
// restart after each apply, but that is operationally heavy for a
// fast-iterating platform config. This endpoint provides a lightweight
// alternative: after `cmd/setup apply`, ops can POST here on each pod to
// force a Refresh without any downtime.
//
// Auth model: gated by CustomizeApplication (same permission that already
// gates layout admin and field-create paths). Non-admin callers get 403.
package rest

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/nexuscrm/backend/internal/application/services"
)

// AdminAutoNumberHandler exposes admin-only maintenance endpoints for
// the autonumber metadata cache.
type AdminAutoNumberHandler struct {
	svcMgr *services.ServiceManager
}

// NewAdminAutoNumberHandler constructs the handler.
func NewAdminAutoNumberHandler(svcMgr *services.ServiceManager) *AdminAutoNumberHandler {
	return &AdminAutoNumberHandler{svcMgr: svcMgr}
}

// RefreshMetadata handles POST /admin/autonumber/refresh-metadata.
// Force-reloads this process's autonumber metadata snapshot from
// _System_Field. Responds 200 with a summary on success, 500 on DB error.
func (h *AdminAutoNumberHandler) RefreshMetadata(c *gin.Context) {
	src := h.svcMgr.AutoNumberMetadata
	if src == nil {
		c.JSON(http.StatusServiceUnavailable, gin.H{
			"error": "autonumber metadata source not initialized",
		})
		return
	}
	if err := src.Refresh(c.Request.Context()); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"error": "autonumber metadata refresh failed",
			"cause": err.Error(),
		})
		return
	}
	// Codex round-8 V2 HIGH: Refresh reloads the metadata snapshot but
	// does not reconcile quarantine state. A field fixed via
	// cmd/setup apply would stay quarantined (stuck broken) until
	// process restart; a newly-malformed rule would not be quarantined
	// and would crash at first insert instead of failing closed. Run
	// ReconcileQuarantine on the fresh snapshot to keep quarantine
	// aligned.
	reconciled := 0
	if eng := h.svcMgr.AutoNumberEngine; eng != nil {
		eng.ReconcileQuarantine(c.Request.Context())
		reconciled = eng.Quarantine().Len()
	}
	c.JSON(http.StatusOK, gin.H{
		"status":               "refreshed",
		"ruleCount":            len(src.ListRules()),
		"quarantinedAfterSync": reconciled,
		"inProcess":            true,
	})
}
