//go:build unit

package crypto

import (
	"os"
	"testing"

	"github.com/centrifuge/pod/utils"
	"github.com/stretchr/testify/assert"
)

var (
	key1      = []byte{0x24, 0xeb, 0x78, 0xef, 0x29, 0xa7, 0xc8, 0xee, 0x49, 0x2d, 0xc4, 0xe6, 0x2f, 0x82, 0x67, 0xfe, 0xc1, 0x4, 0x92, 0xc0, 0x8a, 0x3b, 0x88, 0xda, 0x61, 0x73, 0x85, 0xb1, 0x8c, 0xf1, 0x34, 0xf9, 0x89, 0x2e, 0x3c, 0x26, 0x84, 0xd, 0x9, 0x9f, 0x2a, 0xea, 0x2a, 0x36, 0x6a, 0x4c, 0xff, 0x93, 0xb5, 0xb, 0x1e, 0x2a, 0xb0, 0x3a, 0xb8, 0x1, 0x5, 0xf9, 0xe8, 0x23, 0x7e, 0x92, 0xbb, 0xa1}
	key1Pub   = []byte{0x89, 0x2e, 0x3c, 0x26, 0x84, 0xd, 0x9, 0x9f, 0x2a, 0xea, 0x2a, 0x36, 0x6a, 0x4c, 0xff, 0x93, 0xb5, 0xb, 0x1e, 0x2a, 0xb0, 0x3a, 0xb8, 0x1, 0x5, 0xf9, 0xe8, 0x23, 0x7e, 0x92, 0xbb, 0xa1}
	signature = []byte{0x60, 0x5d, 0xe1, 0xcf, 0x2b, 0x8a, 0xc1, 0xc9, 0x31, 0x6a, 0x42, 0x3f, 0xb9, 0x8d, 0xb7, 0x79, 0x1c, 0x85, 0xc9, 0xc7, 0x24, 0x9f, 0xe8, 0x42, 0x87, 0x50, 0xa4, 0x3f, 0x84, 0xa8, 0xeb, 0x53, 0x8f, 0x81, 0xe1, 0xef, 0x7c, 0xb7, 0x5c, 0x26, 0x7d, 0x5, 0xf3, 0x95, 0x4, 0xef, 0x0, 0x2c, 0x54, 0x47, 0x6e, 0xb9, 0xdc, 0xac, 0x24, 0xeb, 0xe8, 0xc4, 0x98, 0x44, 0x76, 0xf3, 0x76, 0x1}
)

func TestSign(t *testing.T) {
	sig, err := SignMessage(key1, key1Pub, CurveEd25519)
	assert.NoError(t, err)
	assert.NotEmpty(t, sig)
	assert.Len(t, sig, 64)
	assert.Equal(t, signature, sig)
}

func TestValidateSignature_invalid_sig(t *testing.T) {
	pubKey := key1Pub
	message := key1Pub
	signature := utils.RandomSlice(32)
	valid := VerifyMessage(pubKey, message, signature, CurveEd25519)
	assert.False(t, valid, "must be false")
}

func TestSignMessageUnsupportedType(t *testing.T) {
	sig, err := SignMessage(key1, key1Pub, "rsa")
	assert.Error(t, err)
	assert.Empty(t, sig)
}

func TestSignMessageEd25519(t *testing.T) {
	publicKeyFile := "publicKey"
	privateKeyFile := "privateKey"
	testMsg := []byte("test")

	GenerateSigningKeyPair(publicKeyFile, privateKeyFile, CurveEd25519)
	privateKey, err := utils.ReadKeyFromPemFile(privateKeyFile, utils.PrivateKey)
	assert.Nil(t, err)
	publicKey, err := utils.ReadKeyFromPemFile(publicKeyFile, utils.PublicKey)
	assert.Nil(t, err)
	signature, err := SignMessage(privateKey, testMsg, CurveEd25519)
	assert.Nil(t, err)
	correct := VerifyMessage(publicKey, testMsg, signature, CurveEd25519)

	os.Remove(publicKeyFile)
	os.Remove(privateKeyFile)

	assert.True(t, correct, "signature or verification didn't work correctly")
}
