import assert from 'node:assert/strict'
import crypto from 'node:crypto'
import http from 'node:http'
import test from 'node:test'

import { WaHttpRegistrationFlow } from '../WaHttpRegistrationFlow'
import { createNoopLogger } from '../../../infra/log/types'
import { WaAuthMemoryStore } from '../../../store/memory/auth.store'
import { WaPreKeyMemoryStore } from '../../../store/memory/pre-key.store'
import { WaSignalMemoryStore } from '../../../store/memory/signal.store'
import {
    calculateAndroidRegistrationToken,
    calculateRegistrationToken,
    normalizeNationalNumber
} from '../token'
import { REGISTRATION_PUBLIC_KEY, encryptRegistrationPayload } from '../enc'

interface CapturedRequest {
    readonly path: string
    readonly method: string
    readonly headers: http.IncomingHttpHeaders
    readonly rawBody: string
}

interface MockServer {
    readonly requests: CapturedRequest[]
    readonly baseUrl: string
    close(): Promise<void>
}

const TEST_ANDROID_MATERIAL = {
    packageName: 'com.whatsapp',
    secretKey: new Uint8Array(64).fill(7),
    classesDexMd5: new Uint8Array(16).fill(9),
    certificates: [new TextEncoder().encode('test-signing-certificate')],
    apkVersion: '2.26.41.78'
}

async function startMockServer(
    respond: (request: CapturedRequest) => { status: number; body: string }
): Promise<MockServer> {
    const requests: CapturedRequest[] = []
    const server = http.createServer((req, res) => {
        const chunks: Buffer[] = []
        req.on('data', (chunk: Buffer) => chunks.push(chunk))
        req.on('end', () => {
            const captured: CapturedRequest = {
                path: req.url ?? '',
                method: req.method ?? '',
                headers: req.headers,
                rawBody: Buffer.concat(chunks).toString('utf8')
            }
            requests.push(captured)
            const { status, body } = respond(captured)
            res.writeHead(status, { 'Content-Type': 'application/json' })
            res.end(body)
        })
    })
    await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
    const address = server.address()
    const port = typeof address === 'object' && address !== null ? address.port : 0
    return {
        requests,
        baseUrl: `http://127.0.0.1:${port}`,
        close: () => new Promise<void>((resolve) => server.close(() => resolve()))
    }
}

function serverKeyPair(): {
    privateKey: crypto.KeyObject
    publicKeyRaw: Uint8Array
} {
    const { privateKey, publicKey } = crypto.generateKeyPairSync('x25519')
    const jwk = publicKey.export({ format: 'jwk' })
    return { privateKey, publicKeyRaw: Buffer.from(jwk.x!, 'base64url') }
}

/**
 * Decrypt an `ENC=` body the way v.whatsapp.net does: take the ephemeral X25519
 * public key from the front, agree with it, then AES-256-GCM with a zero IV.
 */
function decryptRegistrationBody(rawBody: string, serverPrivateKey: crypto.KeyObject): URLSearchParams {
    assert.ok(rawBody.startsWith('ENC='), 'expected an ENC= body')
    const envelope = Buffer.from(rawBody.slice(4), 'base64url')
    const ephemeralPublic = envelope.subarray(0, 32)
    const sealed = envelope.subarray(32)
    const publicKey = crypto.createPublicKey({
        key: { kty: 'OKP', crv: 'X25519', x: ephemeralPublic.toString('base64url') },
        format: 'jwk'
    })
    const shared = crypto.diffieHellman({ privateKey: serverPrivateKey, publicKey })
    const tag = sealed.subarray(sealed.length - 16)
    const ciphertext = sealed.subarray(0, sealed.length - 16)
    const decipher = crypto.createDecipheriv('aes-256-gcm', shared, Buffer.alloc(12))
    decipher.setAuthTag(tag)
    const plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')
    return new URLSearchParams(plaintext)
}

function createIosFlow(baseUrl: string): {
    flow: WaHttpRegistrationFlow
    serverPrivateKey: crypto.KeyObject
} {
    const server = serverKeyPair()
    const flow = new WaHttpRegistrationFlow({
        logger: createNoopLogger(),
        authStore: new WaAuthMemoryStore(),
        signalStore: new WaSignalMemoryStore(),
        preKeyStore: new WaPreKeyMemoryStore(),
        baseUrl,
        registrationPublicKey: server.publicKeyRaw
    })
    return { flow, serverPrivateKey: server.privateKey }
}

function createFlow(baseUrl: string): {
    flow: WaHttpRegistrationFlow
    authStore: WaAuthMemoryStore
    serverPrivateKey: crypto.KeyObject
} {
    const authStore = new WaAuthMemoryStore()
    const server = serverKeyPair()
    const flow = new WaHttpRegistrationFlow({
        logger: createNoopLogger(),
        authStore,
        signalStore: new WaSignalMemoryStore(),
        preKeyStore: new WaPreKeyMemoryStore(),
        baseUrl,
        androidApkMaterial: TEST_ANDROID_MATERIAL,
        registrationPublicKey: server.publicKeyRaw
    })
    return { flow, authStore, serverPrivateKey: server.privateKey }
}

test('http registration requests a code with the full encrypted parameter set', async () => {
    const server = await startMockServer(() => ({
        status: 200,
        body: JSON.stringify({ status: 'sent', length: 6 })
    }))
    try {
        const { flow, serverPrivateKey } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const result = await flow.requestCode({ cc: '49', in: '15112345678', method: 'sms' })

        assert.equal(result.status, 'sent')
        assert.equal(result.length, 6)
        assert.equal(server.requests.length, 1)

        const request = server.requests[0]
        assert.equal(request.method, 'POST')
        assert.equal(request.path, '/v2/code')
        assert.ok(request.rawBody.startsWith('ENC='), 'body must be the ENC envelope')

        const body = decryptRegistrationBody(request.rawBody, serverPrivateKey)
        assert.equal(body.get('cc'), '49')
        assert.equal(body.get('in'), '15112345678')
        assert.equal(body.get('method'), 'sms')
        assert.ok(body.get('token'), 'expected a registration token')
        assert.ok(body.get('authkey'), 'expected the noise public key as authkey')
        assert.ok(body.get('e_regid'), 'expected the registration id')
        assert.ok(body.get('e_ident'), 'expected the identity public key')
        assert.ok(body.get('e_skey_id'), 'expected the signed pre-key id')
        assert.ok(body.get('e_skey_val'), 'expected the signed pre-key')
        assert.ok(body.get('e_skey_sig'), 'expected the signed pre-key signature')
        assert.equal(request.headers['wamsysrequest'], '1')
        assert.ok(request.headers['request_token'], 'expected a request token header')
        assert.equal(
            request.headers['user-agent'],
            'WhatsApp/2.26.41.78 Android/14 Device/Google-panther',
            'expected the WhatsApp android user agent built from the device info'
        )
    } finally {
        await server.close()
    }
})

test('http registration sends a fresh identity triple per request', async () => {
    const server = await startMockServer(() => ({
        status: 200,
        body: JSON.stringify({ status: 'sent' })
    }))
    try {
        const { flow, serverPrivateKey } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        await flow.requestCode({ cc: '49', in: '15112345678' })
        await flow.requestCode({ cc: '49', in: '15112345678' })

        const [first, second] = server.requests.map((request) =>
            decryptRegistrationBody(request.rawBody, serverPrivateKey)
        )
        assert.equal(
            Buffer.from(first.get('expid') ?? '', 'base64url').length,
            16,
            'expected a 16 byte experiment id'
        )
        assert.equal(
            Buffer.from(first.get('id') ?? '', 'utf8').length > 0,
            true,
            'expected a request id'
        )
        assert.notEqual(first.get('expid'), second.get('expid'))
        assert.notEqual(first.get('id'), second.get('id'))
        assert.equal(
            first.get('fdid'),
            second.get('fdid'),
            'the device id must stay stable across requests of one registration'
        )
    } finally {
        await server.close()
    }
})

test('http registration submits the verification code', async () => {
    const server = await startMockServer((request) => ({
        status: 200,
        body: JSON.stringify(
            request.path.startsWith('/v2/register')
                ? { status: 'ok', login: '4915112345678', pw: 'secret', type: 'sms' }
                : { status: 'sent' }
        )
    }))
    try {
        const { flow, serverPrivateKey } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const result = await flow.register({ cc: '49', in: '15112345678', code: '123456' })

        assert.equal(result.status, 'ok')
        assert.equal(result.login, '4915112345678')
        assert.equal(result.pw, 'secret')

        const request = server.requests[0]
        assert.equal(request.path, '/v2/register')
        const body = decryptRegistrationBody(request.rawBody, serverPrivateKey)
        assert.equal(body.get('code'), '123456')
        assert.equal(body.get('entered'), '1')
    } finally {
        await server.close()
    }
})

test('http registration persists the mobile primary credentials', async () => {
    const server = await startMockServer((request) => ({
        status: 200,
        body: JSON.stringify(
            request.path.startsWith('/v2/register')
                ? { status: 'ok', login: '4915112345678' }
                : { status: 'sent' }
        )
    }))
    try {
        const { flow, authStore } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const registered = await flow.registerPhone({
            cc: '49',
            in: '15112345678',
            method: 'sms',
            code: '123456',
            pushName: 'Tester'
        })

        assert.equal(registered.meJid, '4915112345678@s.whatsapp.net')
        assert.equal(registered.login, '4915112345678')
        assert.equal(registered.credentials.pushName, 'Tester')
        assert.ok(registered.deviceInfo.appVersion)

        const persisted = await authStore.load()
        assert.equal(persisted?.meJid, '4915112345678@s.whatsapp.net')
        assert.equal(persisted?.pushName, 'Tester')
    } finally {
        await server.close()
    }
})

test('http registration reports the reason of a rejected registration', async () => {
    const server = await startMockServer(() => ({
        status: 400,
        body: JSON.stringify({ status: 'fail', reason: 'code-expired' })
    }))
    try {
        const { flow } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const result = await flow.register({ cc: '49', in: '15112345678', code: '000000' })

        assert.equal(result.status, 'fail')
        assert.equal(result.reason, 'code-expired')
    } finally {
        await server.close()
    }
})

test('http registration checks whether a number is known to the server', async () => {
    const server = await startMockServer(() => ({
        status: 200,
        body: JSON.stringify({ status: 'ok', length: 6, country: '49' })
    }))
    try {
        const { flow, serverPrivateKey } = createFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const result = (await flow.checkExist({ cc: '49', in: '15112345678' })) as {
            status: string
            length: number
        }

        assert.equal(result.status, 'ok')
        assert.equal(result.length, 6)

        const request = server.requests[0]
        assert.equal(request.path, '/v2/exist')
        const body = decryptRegistrationBody(request.rawBody, serverPrivateKey)
        assert.ok(body.get('expid'), 'expected an experiment id')
        assert.ok(body.get('id'), 'expected a request id')
        assert.ok(body.get('fdid'), 'expected a device id')
        assert.equal(body.get('token'), null, '/exist carries no token')
    } finally {
        await server.close()
    }
})

test('http registration refuses to work before the keys are loaded', async () => {
    const server = await startMockServer(() => ({ status: 200, body: '{}' }))
    try {
        const { flow } = createFlow(server.baseUrl)
        await assert.rejects(
            () => flow.requestCode({ cc: '49', in: '15112345678' }),
            /Credentials not loaded/
        )
    } finally {
        await server.close()
    }
})

test('iOS registration needs no APK material and uses the iOS token formula', async () => {
    const server = await startMockServer(() => ({
        status: 200,
        body: JSON.stringify({ status: 'sent', length: 6 })
    }))
    try {
        const { flow, serverPrivateKey } = createIosFlow(server.baseUrl)
        await flow.loadOrCreateKeys()

        const result = await flow.requestCode({
            cc: '49',
            in: '15112345678',
            deviceInfo: { os: 'ios' }
        })
        assert.equal(result.status, 'sent')

        const request = server.requests[0]
        assert.equal(request.headers['user-agent'], 'WhatsApp/2.26.41.74 iOS/17.4.1 Device/iPhone 15 Pro')
        assert.equal(request.headers['wamsysrequest'], undefined)
        const body = decryptRegistrationBody(request.rawBody, serverPrivateKey)
        assert.match(body.get('token') ?? '', /^[0-9a-f]{32}$/)
    } finally {
        await server.close()
    }
})

test('Android registration refuses to build a token without APK material', () => {
    assert.throws(
        () => calculateRegistrationToken('2.26.41.78', '15112345678', { os: 'android' }),
        /APK material/
    )
})

// ---------- token / ENC primitives ----------

test('iOS token hashes the national number, not cc + national', () => {
    const national = calculateRegistrationToken('2.26.41.74', '015112345678')
    assert.equal(national, calculateRegistrationToken('2.26.41.74', '15112345678'))
    assert.notEqual(national, calculateRegistrationToken('2.26.41.74', '4915112345678'))
    assert.match(national, /^[0-9a-f]{32}$/)
    assert.equal(normalizeNationalNumber('0015112345678'), '15112345678')
})

test('Android token is HMAC-SHA1 material encoded as urlencoded base64', () => {
    const token = calculateAndroidRegistrationToken('15112345678', {
        androidMaterial: TEST_ANDROID_MATERIAL
    })
    const decoded = Buffer.from(decodeURIComponent(token), 'base64')
    assert.equal(decoded.length, 20, 'HMAC-SHA1 digest is 20 bytes')
    assert.equal(
        token,
        calculateAndroidRegistrationToken('15112345678', {
            androidMaterial: TEST_ANDROID_MATERIAL
        })
    )
    assert.notEqual(
        token,
        calculateAndroidRegistrationToken('15112345679', {
            androidMaterial: TEST_ANDROID_MATERIAL
        })
    )
})

test('registration ENC envelope is X25519 + AES-256-GCM and decrypts back', async () => {
    assert.equal(REGISTRATION_PUBLIC_KEY.length, 32)
    const server = serverKeyPair()
    const plaintext = 'cc=49&in=15112345678&token=deadbeef'
    const envelope = await encryptRegistrationPayload(plaintext, {
        serverPublicKey: server.publicKeyRaw
    })
    const raw = Buffer.from(envelope, 'base64url')
    assert.equal(raw.length, 32 + plaintext.length + 16)
    const decoded = decryptRegistrationBody(`ENC=${envelope}`, server.privateKey)
    assert.equal(decoded.toString(), plaintext)
})
