package approval_test

import (
	"testing"
	"time"

	"github.com/acp/interceptor/internal/approval"
	"github.com/acp/interceptor/internal/audit"
)

func TestSyncPendingFromAudit(t *testing.T) {
	t.Parallel()

	store := approval.NewStore(10)
	events := []audit.Event{
		{
			TraceID:  "trace-a",
			AgentID:  "uw",
			Tool:     "underwriting_api",
			Action:   "score_loan",
			Decision: "escalate",
			Reason:   "loan_amount_requires_senior_uw",
			Policy:   "acp/mortgage_underwriting",
			Timestamp: time.Now().UTC(),
		},
		{
			TraceID:  "trace-a",
			Decision: "escalate",
			Reason:   "approval_pending",
		},
	}

	approval.SyncPendingFromAudit(store, events)
	rec, ok := store.Get("trace-a")
	if !ok || rec.Status != approval.StatusPending {
		t.Fatalf("expected pending ticket, got %#v ok=%v", rec, ok)
	}

	pending := store.List(approval.StatusPending, 10)
	if len(pending) != 1 {
		t.Fatalf("expected 1 pending, got %d", len(pending))
	}

	_, _ = store.Approve("trace-a", "supervisor")
	approval.SyncPendingFromAudit(store, events)
	approved, ok := store.Get("trace-a")
	if !ok || approved.Status != approval.StatusApproved {
		t.Fatalf("sync must not reopen approved ticket, got %#v", approved)
	}
	if len(store.List(approval.StatusPending, 10)) != 0 {
		t.Fatal("expected no pending after approve + sync")
	}
}
