package canon_test

import (
	"bytes"
	"crypto/ed25519"
	"encoding/hex"
	"testing"

	"galaxy/core/canon"

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

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

	base := canon.ResponseSigningFields{
		ProtocolVersion: "v1",
		RequestID:       "request-123",
		TimestampMS:     123456789,
		ResultCode:      "ok",
		PayloadHash:     sha256Sum([]byte("payload")),
	}

	baseInput := canon.BuildResponseSigningInput(base)

	tests := []struct {
		name   string
		mutate func(canon.ResponseSigningFields) canon.ResponseSigningFields
	}{
		{
			name: "protocol version",
			mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields {
				fields.ProtocolVersion = "v2"
				return fields
			},
		},
		{
			name: "request id",
			mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields {
				fields.RequestID = "request-456"
				return fields
			},
		},
		{
			name: "timestamp",
			mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields {
				fields.TimestampMS++
				return fields
			},
		},
		{
			name: "result code",
			mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields {
				fields.ResultCode = "denied"
				return fields
			},
		},
		{
			name: "payload hash",
			mutate: func(fields canon.ResponseSigningFields) canon.ResponseSigningFields {
				fields.PayloadHash = sha256Sum([]byte("other"))
				return fields
			},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()

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

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

	seed := bytes.Repeat([]byte{0xAA}, ed25519.SeedSize)
	privateKey := ed25519.NewKeyFromSeed(seed)
	publicKey, _ := privateKey.Public().(ed25519.PublicKey)

	fields := canon.ResponseSigningFields{
		ProtocolVersion: "v1",
		RequestID:       "request-123",
		TimestampMS:     123456789,
		ResultCode:      "ok",
		PayloadHash:     sha256Sum([]byte("payload")),
	}

	signature := ed25519.Sign(privateKey, canon.BuildResponseSigningInput(fields))
	require.NoError(t, canon.VerifyResponseSignature(publicKey, signature, fields))

	t.Run("rejects mutated field", func(t *testing.T) {
		t.Parallel()

		mutated := fields
		mutated.ResultCode = "denied"
		require.ErrorIs(t,
			canon.VerifyResponseSignature(publicKey, signature, mutated),
			canon.ErrInvalidResponseSignature)
	})

	t.Run("rejects invalid public key length", func(t *testing.T) {
		t.Parallel()

		shortKey := publicKey[:len(publicKey)-1]
		require.ErrorIs(t,
			canon.VerifyResponseSignature(shortKey, signature, fields),
			canon.ErrInvalidResponseSignature)
	})

	t.Run("rejects invalid signature length", func(t *testing.T) {
		t.Parallel()

		require.ErrorIs(t,
			canon.VerifyResponseSignature(publicKey, signature[:len(signature)-1], fields),
			canon.ErrInvalidResponseSignature)
	})
}

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

	var fx responseFixture
	loadJSONFixture(t, "response_ok.json", &fx)

	fields := canon.ResponseSigningFields{
		ProtocolVersion: fx.ProtocolVersion,
		RequestID:       fx.RequestID,
		TimestampMS:     fx.TimestampMS,
		ResultCode:      fx.ResultCode,
		PayloadHash:     mustHex(t, fx.PayloadHashHex),
	}

	require.NoError(t,
		canon.VerifyPayloadHash([]byte(fx.Payload), fields.PayloadHash))

	gotInput := canon.BuildResponseSigningInput(fields)
	assert.Equal(t, fx.ExpectedCanonicalBytesHex, hex.EncodeToString(gotInput))

	seed := mustHex(t, fx.PrivateKeySeedHex)
	require.Len(t, seed, ed25519.SeedSize)
	privateKey := ed25519.NewKeyFromSeed(seed)
	publicKey, _ := privateKey.Public().(ed25519.PublicKey)
	signature := ed25519.Sign(privateKey, gotInput)
	assert.Equal(t, fx.ExpectedSignatureHex, hex.EncodeToString(signature))

	require.NoError(t, canon.VerifyResponseSignature(publicKey, signature, fields))
}
