package authn

import (
	"bytes"
	"crypto/ed25519"
	"crypto/rand"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

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

	base := EventSigningFields{
		EventType:   "gateway.server_time",
		EventID:     "request-123",
		TimestampMS: 123456789,
		RequestID:   "request-123",
		TraceID:     "trace-123",
		PayloadHash: mustSHA256([]byte("payload")),
	}

	baseInput := BuildEventSigningInput(base)

	tests := []struct {
		name   string
		mutate func(EventSigningFields) EventSigningFields
	}{
		{
			name: "event type",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.EventType = "gateway.other"
				return fields
			},
		},
		{
			name: "event id",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.EventID = "request-456"
				return fields
			},
		},
		{
			name: "timestamp",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.TimestampMS++
				return fields
			},
		},
		{
			name: "request id",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.RequestID = "request-456"
				return fields
			},
		},
		{
			name: "trace id",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.TraceID = "trace-456"
				return fields
			},
		},
		{
			name: "payload hash",
			mutate: func(fields EventSigningFields) EventSigningFields {
				fields.PayloadHash = mustSHA256([]byte("other"))
				return fields
			},
		},
	}

	for _, tt := range tests {
		tt := tt

		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

			mutated := BuildEventSigningInput(tt.mutate(base))
			assert.False(t, bytes.Equal(baseInput, mutated))
		})
	}
}

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

	_, privateKey, err := ed25519.GenerateKey(rand.Reader)
	require.NoError(t, err)

	signer, err := NewEd25519ResponseSigner(privateKey)
	require.NoError(t, err)

	fields := EventSigningFields{
		EventType:   "gateway.server_time",
		EventID:     "request-123",
		TimestampMS: 123456789,
		RequestID:   "request-123",
		TraceID:     "trace-123",
		PayloadHash: mustSHA256([]byte("payload")),
	}

	signature, err := signer.SignEvent(fields)
	require.NoError(t, err)
	require.NoError(t, VerifyEventSignature(signer.PublicKey(), signature, fields))

	fields.TraceID = "changed"
	require.ErrorIs(t, VerifyEventSignature(signer.PublicKey(), signature, fields), ErrInvalidEventSignature)
}
