package librpki

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"math/big"
	"testing"

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

func TestEncodeTAL(t *testing.T) {
	privkey, _ := rsa.GenerateKey(rand.Reader, 2048)

	tal, err := CreateTAL([]string{"rsync://example.com/module/root.cer"}, privkey.Public())
	assert.Nil(t, err)

	_, err = EncodeTAL(tal)
	assert.Nil(t, err)
}

func TestDecodeTAL(t *testing.T) {
	data := `rsync://rpki.apnic.net/repository/apnic-rpki-root-iana-origin.cer

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx9RWSL61YAAYumEiU8z8
qH2ETVIL01ilxZlzIL9JYSORMN5Cmtf8V2JblIealSqgOTGjvSjEsiV73s67zYQI
7C/iSOb96uf3/s86NqbxDiFQGN8qG7RNcdgVuUlAidl8WxvLNI8VhqbAB5uSg/Mr
LeSOvXRja041VptAxIhcGzDMvlAJRwkrYK/Mo8P4E2rSQgwqCgae0ebY1CsJ3Cjf
i67C1nw7oXqJJovvXJ4apGmEv8az23OLC6Ki54Ul/E6xk227BFttqFV3YMtKx42H
cCcDVZZy01n7JjzvO8ccaXmHIgR7utnqhBRNNq5Xc5ZhbkrUsNtiJmrZzVlgU6Ou
0wIDAQAB
`

	key := []byte{
		0xC7, 0xD4, 0x56, 0x48, 0xBE, 0xB5,
		0x60, 0x00, 0x18, 0xBA, 0x61, 0x22, 0x53, 0xCC, 0xFC, 0xA8, 0x7D,
		0x84, 0x4D, 0x52, 0x0B, 0xD3, 0x58, 0xA5, 0xC5, 0x99, 0x73, 0x20,
		0xBF, 0x49, 0x61, 0x23, 0x91, 0x30, 0xDE, 0x42, 0x9A, 0xD7, 0xFC,
		0x57, 0x62, 0x5B, 0x94, 0x87, 0x9A, 0x95, 0x2A, 0xA0, 0x39, 0x31,
		0xA3, 0xBD, 0x28, 0xC4, 0xB2, 0x25, 0x7B, 0xDE, 0xCE, 0xBB, 0xCD,
		0x84, 0x08, 0xEC, 0x2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0, 0xDB, 0x62, 0x26, 0x6A,
		0xD9, 0xCD, 0x59, 0x60, 0x53, 0xA3, 0xAE, 0xD3,
	}
	bigint := big.NewInt(0)
	bigint.SetBytes(key)

	tal, err := DecodeTAL([]byte(data))
	assert.Nil(t, err)
	assert.Equal(t, tal.PublicKey.(*rsa.PublicKey).E, 65537)

	cert := &x509.Certificate{
		PublicKeyAlgorithm: x509.RSA,
		PublicKey: &rsa.PublicKey{
			E: 65537,
			N: bigint,
		},
	}
	assert.Equal(t, tal.CheckCertificate(cert), true)
}
