import { defaultCryptoProvider } from '@mtcute/test'
import { beforeAll, describe, expect, it } from 'vitest'

import { findKeyByFingerprints, parsePublicKey } from '../index.js'

const crypto = defaultCryptoProvider

beforeAll(async () => {
    await crypto.initialize()
})

describe('parsePublicKey', () => {
    it('should parse telegram public keys', () => {
        expect(
            parsePublicKey(
                crypto,
                `-----BEGIN RSA PUBLIC KEY-----
MIIBCgKCAQEAruw2yP/BCcsJliRoW5eBVBVle9dtjJw+OYED160Wybum9SXtBBLX
riwt4rROd9csv0t0OHCaTmRqBcQ0J8fxhN6/cpR1GWgOZRUAiQxoMnlt0R93LCX/
j1dnVa/gVbCjdSxpbrfY2g2L4frzjJvdl84Kd9ORYjDEAyFnEA7dD556OptgLQQ2
e2iVNq8NZLYTzLp5YpOdO1doK+ttrltggTCy5SrKeLoCPPbOgGsdxJxyz5KKcZnS
Lj16yE5HvJQn0CNpRdENvRUXe6tBP78O39oJ8BTHp9oIjd6XWXAsp2CvK45Ol8wF
XGF710w9lwCGNbmNxNYhtIkdqfsEcwR5JwIDAQAB
-----END RSA PUBLIC KEY-----`,
            ),
        ).eql({
            modulus:
                'aeec36c8ffc109cb099624685b97815415657bd76d8c9c3e398103d7ad16c9bba6f525ed0412d7ae2c2de2b44e77d72cbf4b7438709a4e646a05c43427c7f184debf72947519680e651500890c6832796dd11f772c25ff8f576755afe055b0a3752c696eb7d8da0d8be1faf38c9bdd97ce0a77d3916230c4032167100edd0f9e7a3a9b602d04367b689536af0d64b613ccba7962939d3b57682beb6dae5b608130b2e52aca78ba023cf6ce806b1dc49c72cf928a7199d22e3d7ac84e47bc9427d0236945d10dbd15177bab413fbf0edfda09f014c7a7da088dde9759702ca760af2b8e4e97cc055c617bd74c3d97008635b98dc4d621b4891da9fb0473047927',
            exponent: '010001',
            fingerprint: '0bc35f3509f7b7a5',
            old: false,
        })
    })

    it('should be able to find a key by its fingerprint', () => {
        expect(findKeyByFingerprints(['b25898df208d2603'])).toMatchInlineSnapshot(`
          {
            "exponent": "010001",
            "fingerprint": "b25898df208d2603",
            "modulus": "c8c11d635691fac091dd9489aedced2932aa8a0bcefef05fa800892d9b52ed03200865c9e97211cb2ee6c7ae96d3fb0e15aeffd66019b44a08a240cfdd2868a85e1f54d6fa5deaa041f6941ddf302690d61dc476385c2fa655142353cb4e4b59f6e5b6584db76fe8b1370263246c010c93d011014113ebdf987d093f9d37c2be48352d69a1683f8f6e6c2167983c761e3ab169fde5daaa12123fa1beab621e4da5935e9c198f82f35eae583a99386d8110ea6bd1abb0f568759f62694419ea5f69847c43462abef858b4cb5edc84e7b9226cd7bd7e183aa974a712c079dde85b9dc063b8a5c08e8f859c0ee5dcd824c7807f20153361a7f63cfd2a433a1be7f5",
            "old": false,
          }
        `)
    })

    it('should prefer new keys over old', () => {
        expect(findKeyByFingerprints(['71e025b6c76033e3', 'b25898df208d2603'])?.fingerprint).toEqual('b25898df208d2603')
    })

    it('should return null if not found', () => {
        expect(findKeyByFingerprints(['deadbeefdeadbeef'])).toBeNull()
    })
})
