package approval

import (
	"github.com/acp/interceptor/internal/audit"
	"github.com/acp/interceptor/internal/models"
)

// SyncPendingFromAudit creates pending tickets for policy escalations that do not yet
// have an approval record (e.g. interceptor restarted or traffic before approval API existed).
func SyncPendingFromAudit(store Repository, events []audit.Event) {
	if store == nil || len(events) == 0 {
		return
	}
	seen := make(map[string]struct{})
	for _, e := range events {
		if e.Decision != "escalate" {
			continue
		}
		if e.Reason == "approval_pending" {
			continue
		}
		if e.TraceID == "" {
			continue
		}
		if _, dup := seen[e.TraceID]; dup {
			continue
		}
		seen[e.TraceID] = struct{}{}

		if _, ok := store.Get(e.TraceID); ok {
			// Never reopen decided tickets from historical escalate audit lines.
			continue
		}

		req := models.ToolCallRequest{
			AgentID:   e.AgentID,
			Tool:      e.Tool,
			Action:    e.Action,
			Amount:    e.Amount,
			RiskScore: e.RiskScore,
		}
		policy := e.Policy
		if policy == "" {
			policy = "acp/unknown"
		}
		store.UpsertPending(e.TraceID, req, e.Reason, policy)
	}
}
