package persistence

import (
	"testing"
)

func TestOutboxRecordKeyFromPayload(t *testing.T) {
	tests := []struct {
		name    string
		payload string
		want    string
	}{
		{
			name:    "internal envelope",
			payload: `{"public_payload":{"object_api_name":"Account","record":{"Id":"001-record"}}}`,
			want:    "Account/001-record",
		},
		{
			name:    "legacy payload",
			payload: `{"object_api_name":"Contact","record":{"Id":"003-record"}}`,
			want:    "Contact/003-record",
		},
		{
			name:    "malformed falls back to event id",
			payload: `{"public_payload":`,
			want:    "evt-fallback",
		},
		{
			name:    "missing record id falls back to event id",
			payload: `{"public_payload":{"object_api_name":"Account","record":{}}}`,
			want:    "evt-fallback",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := outboxRecordKeyFromPayload([]byte(tt.payload), "evt-fallback"); got != tt.want {
				t.Fatalf("record key = %q, want %q", got, tt.want)
			}
		})
	}
}

func mustRecordEventScopeDigest(t *testing.T, scope RuntimeWorkScope) string {
	t.Helper()
	digest, err := scope.Digest()
	if err != nil {
		t.Fatal(err)
	}
	return digest
}
