import { X25519 } from '../../crypto'
import { aesGcmEncrypt } from '../../crypto/core/primitives'
import {
    bytesToBase64,
    concatBytes,
    hexToBytes,
    TEXT_ENCODER
} from '../../util/bytes'

/**
 * WhatsApp's registration server static X25519 public key.
 *
 * This is NOT an RSA key. The old `ENC=` envelope is an ephemeral
 * X25519 Diffie-Hellman agreement with this key, followed by AES-256-GCM:
 *
 *   eph    = fresh X25519 key pair (one per request)
 *   shared = X25519(eph.priv, SERVER_PUBLIC_KEY)
 *   sealed = AES-256-GCM(shared, nonce = 12 zero bytes, plaintext)
 *   ENC    = base64url(eph.pub || sealed)   // sealed = ciphertext || tag
 *
 * The 0x05 byte that appears in historical listings is the libsignal public
 * key type prefix; the raw key is 32 bytes.
 */
const REGISTRATION_SERVER_PUBLIC_KEY_HEX =
    '8e8c0f74c3ebc5d7a6865c6c3c843856b06121cce8ea774d22fb6f122512302d'

export const REGISTRATION_PUBLIC_KEY: Readonly<Uint8Array> = hexToBytes(
    REGISTRATION_SERVER_PUBLIC_KEY_HEX
)

export interface RegistrationEncryptionOptions {
    /** Override the server key (tests / future rotation). */
    readonly serverPublicKey?: Uint8Array
}

/**
 * Build the `ENC=` value for a registration request.
 *
 * `plaintextForm` is the native client's query string (`cc=..&in=..&token=..`).
 * Values are already in their wire form: base64url for keys, `%XX` for `id`,
 * percent-encoded base64 for the Android token.
 */
export async function encryptRegistrationPayload(
    plaintextForm: string | Uint8Array,
    options: RegistrationEncryptionOptions = {}
): Promise<string> {
    const configuredKey = options.serverPublicKey ?? REGISTRATION_PUBLIC_KEY
    // Accept the historical libsignal form (0x05 prefix + 32 bytes) too.
    const serverPublicKey =
        configuredKey.length === 33 && configuredKey[0] === 0x05
            ? configuredKey.subarray(1)
            : configuredKey
    if (serverPublicKey.length !== 32) {
        throw new Error(
            `registration server public key must be 32 bytes, got ${serverPublicKey.length}`
        )
    }

    const ephemeral = await X25519.generateKeyPair()
    const shared = await X25519.scalarMult(ephemeral.privKey, serverPublicKey)
    const plaintext =
        typeof plaintextForm === 'string' ? TEXT_ENCODER.encode(plaintextForm) : plaintextForm

    // Fresh ephemeral key per request means a fixed all-zero nonce is safe here;
    // it is what the native client sends.
    const nonce = new Uint8Array(12)
    const sealed = aesGcmEncrypt(shared, nonce, plaintext)
    return bytesToBase64Url(concatBytes([ephemeral.pubKey, sealed]))
}

/**
 * URL-safe base64 WITH padding. Java's `Base64.getUrlEncoder()` keeps the `=`
 * padding, and the native client sends it that way.
 */
function bytesToBase64Url(value: Uint8Array): string {
    return bytesToBase64(value).replace(/\+/g, '-').replace(/\//g, '_')
}

/** Full `application/x-www-form-urlencoded` body: `ENC=<base64url>`. */
export async function buildEncryptedRegistrationBody(
    plaintextForm: string | Uint8Array,
    options: RegistrationEncryptionOptions = {}
): Promise<string> {
    return `ENC=${await encryptRegistrationPayload(plaintextForm, options)}`
}
