/** Per-connection lifecycle pipeline (Noise handshake + stanza loop). */

import { buildFakeCertChain, type FakeNoiseRootCa } from '../protocol/auth/cert-chain'
import {
    parseClientPayload,
    type ParsedClientPayload
} from '../protocol/auth/client-payload-validate'
import { buildSuccessNode } from '../protocol/auth/success-node'
import { type BinaryNode, decodeBinaryNodeStanza, encodeBinaryNodeStanza } from '../transport/codec'
import { type SignalKeyPair, X25519 } from '../transport/crypto'
import { proto } from '../transport/protos'

import type { WaFakeConnection } from './WaFakeConnection'
import { type WaFakeClientPrologue, WaFakeFrameSocket } from './WaFakeFrameSocket'
import { WaFakeNoiseHandshake } from './WaFakeNoiseHandshake'
import { WaFakeTransport } from './WaFakeTransport'

const NOISE_XX_NAME = new TextEncoder().encode('Noise_XX_25519_AESGCM_SHA256\0\0\0\0')
const NOISE_IK_NAME = new TextEncoder().encode('Noise_IK_25519_AESGCM_SHA256\0\0\0\0')
const PROLOGUE_MAGIC_W = 0x57
const PROLOGUE_MAGIC_A = 0x41
const DEFAULT_PROLOGUE = new Uint8Array([PROLOGUE_MAGIC_W, PROLOGUE_MAGIC_A, 0x06, 0x03])

export interface WaFakeConnectionPipelineConfig {
    readonly connection: WaFakeConnection
    readonly rootCa: FakeNoiseRootCa
    readonly serverStaticKeyPair: SignalKeyPair
    /**
     * Routes an inbound IQ against the session this connection is bound to.
     * The server resolves the session per connection, so the pipeline stays
     * unaware of session identity.
     */
    readonly routeIq: (iq: BinaryNode) => Promise<BinaryNode | null>
    readonly successNodeAttributes?: Parameters<typeof buildSuccessNode>[0]
}

export interface WaFakeConnectionPipelineEvents {
    readonly onAuthenticated?: (info: WaFakeAuthenticatedInfo) => void
    readonly onStanza?: (node: BinaryNode) => void
    readonly onUnhandledStanza?: (node: BinaryNode) => void
    readonly onError?: (error: Error) => void
    readonly onClose?: (info: { readonly code: number; readonly reason: string }) => void
}

export interface WaFakeAuthenticatedInfo {
    readonly clientPayload: ParsedClientPayload
    readonly clientStaticKey: Uint8Array
}

type State =
    | { readonly kind: 'awaiting_prologue' }
    | { readonly kind: 'awaiting_client_hello' }
    | {
          readonly kind: 'awaiting_client_finish'
          readonly handshake: WaFakeNoiseHandshake
          readonly serverEphemeralKeyPair: SignalKeyPair
          readonly clientEphemeralPub: Uint8Array
      }
    | {
          readonly kind: 'authenticated'
          readonly transport: WaFakeTransport
      }
    | { readonly kind: 'closed' }

export class WaFakeConnectionPipeline {
    private readonly config: WaFakeConnectionPipelineConfig
    private readonly frameSocket: WaFakeFrameSocket
    private events: WaFakeConnectionPipelineEvents = {}
    private state: State = { kind: 'awaiting_prologue' }
    private chain: Promise<void> = Promise.resolve()
    private authenticatedPayload: ParsedClientPayload | null = null
    private clientPrologue: Uint8Array = DEFAULT_PROLOGUE

    public constructor(config: WaFakeConnectionPipelineConfig) {
        this.config = config
        this.frameSocket = new WaFakeFrameSocket(config.connection)
        this.frameSocket.setHandlers({
            onPrologue: (prologue) => this.onPrologue(prologue),
            onFrame: (frame) => this.scheduleFrame(frame),
            onClose: (info) => {
                this.state = { kind: 'closed' }
                this.events.onClose?.(info)
            },
            onError: (error) => this.events.onError?.(error)
        })
    }

    public setEvents(events: WaFakeConnectionPipelineEvents): void {
        this.events = events
    }

    public isAuthenticated(): boolean {
        return this.state.kind === 'authenticated'
    }

    /** Parsed ClientPayload of the authenticated connection; null before auth. */
    public get clientPayload(): ParsedClientPayload | null {
        return this.authenticatedPayload
    }

    public async sendStanza(node: BinaryNode): Promise<void> {
        if (this.state.kind !== 'authenticated') {
            throw new Error(`cannot send stanza while pipeline is in state "${this.state.kind}"`)
        }
        const stanza = encodeBinaryNodeStanza(node)
        // Keep outbound encrypted frames in FIFO order across concurrent callers.
        const ciphertext = await this.state.transport.encryptFrame(stanza)
        this.frameSocket.sendFrame(ciphertext)
    }

    private onPrologue(prologue: WaFakeClientPrologue): void {
        if (this.state.kind !== 'awaiting_prologue') {
            this.events.onError?.(new Error('received second prologue from client'))
            return
        }
        // Mix back the header the client actually sent instead of a fixed one:
        // it is hashed into the handshake, and a client is free to advertise a
        // protocol/dict version other than the web client's 6/3.
        this.clientPrologue = new Uint8Array([
            PROLOGUE_MAGIC_W,
            PROLOGUE_MAGIC_A,
            prologue.protocolVersion,
            prologue.dictVersion
        ])
        this.state = { kind: 'awaiting_client_hello' }
    }

    private scheduleFrame(frame: Uint8Array): void {
        this.chain = this.chain.then(() => this.handleFrame(frame))
    }

    private async handleFrame(frame: Uint8Array): Promise<void> {
        try {
            switch (this.state.kind) {
                case 'awaiting_client_hello':
                    await this.handleClientHello(frame)
                    return
                case 'awaiting_client_finish':
                    await this.handleClientFinish(
                        frame,
                        this.state.handshake,
                        this.state.serverEphemeralKeyPair
                    )
                    return
                case 'authenticated':
                    await this.handleAuthenticatedFrame(frame, this.state.transport)
                    return
                default:
                    this.events.onError?.(
                        new Error(`unexpected frame in state "${this.state.kind}"`)
                    )
            }
        } catch (error) {
            this.fail(error)
        }
    }

    private async handleClientHello(frame: Uint8Array): Promise<void> {
        const parsed = proto.HandshakeMessage.decode(frame)
        const clientHello = parsed.clientHello
        if (!clientHello?.ephemeral) {
            throw new Error('ClientHello missing ephemeral')
        }

        // IK includes encrypted static+payload in ClientHello; XX does not.
        if (clientHello.static && clientHello.payload) {
            await this.handleIkClientHello(clientHello)
        } else {
            await this.handleXxClientHello(clientHello.ephemeral)
        }
    }

    private async handleXxClientHello(clientEphemeralPub: Uint8Array): Promise<void> {
        const handshake = new WaFakeNoiseHandshake()
        handshake.start(NOISE_XX_NAME, this.clientPrologue)
        handshake.authenticate(clientEphemeralPub)

        const serverEphemeral = await X25519.generateKeyPair()
        handshake.authenticate(serverEphemeral.pubKey)
        handshake.mixIntoKey(await X25519.scalarMult(serverEphemeral.privKey, clientEphemeralPub))
        const encryptedServerStatic = handshake.encrypt(this.config.serverStaticKeyPair.pubKey)
        handshake.mixIntoKey(
            await X25519.scalarMult(this.config.serverStaticKeyPair.privKey, clientEphemeralPub)
        )

        const certChain = await buildFakeCertChain({
            root: this.config.rootCa,
            leafKey: this.config.serverStaticKeyPair.pubKey
        })
        const encryptedCertPayload = handshake.encrypt(certChain.encoded)

        const serverHello = proto.HandshakeMessage.encode({
            serverHello: {
                ephemeral: serverEphemeral.pubKey,
                static: encryptedServerStatic,
                payload: encryptedCertPayload
            }
        }).finish()

        this.frameSocket.sendFrame(serverHello)

        this.state = {
            kind: 'awaiting_client_finish',
            handshake,
            serverEphemeralKeyPair: serverEphemeral,
            clientEphemeralPub
        }
    }

    /** Server-side IK path used when the client already cached our static key. */
    private async handleIkClientHello(clientHello: {
        readonly ephemeral?: Uint8Array | null
        readonly static?: Uint8Array | null
        readonly payload?: Uint8Array | null
    }): Promise<void> {
        if (!clientHello.ephemeral || !clientHello.static || !clientHello.payload) {
            throw new Error('IK ClientHello missing ephemeral/static/payload')
        }
        const clientEphemeralPub = clientHello.ephemeral
        const encryptedClientStatic = clientHello.static
        const encryptedClientPayload = clientHello.payload

        const handshake = new WaFakeNoiseHandshake()
        handshake.start(NOISE_IK_NAME, this.clientPrologue)
        handshake.authenticate(this.config.serverStaticKeyPair.pubKey)
        handshake.authenticate(clientEphemeralPub)
        handshake.mixIntoKey(
            await X25519.scalarMult(this.config.serverStaticKeyPair.privKey, clientEphemeralPub)
        )
        const clientStaticKey = handshake.decrypt(encryptedClientStatic)
        handshake.mixIntoKey(
            await X25519.scalarMult(this.config.serverStaticKeyPair.privKey, clientStaticKey)
        )
        const clientPayloadBytes = handshake.decrypt(encryptedClientPayload)
        const clientPayload = parseClientPayload(clientPayloadBytes)

        const serverEphemeral = await X25519.generateKeyPair()
        handshake.authenticate(serverEphemeral.pubKey)
        const [dhEphem, dhStatic] = await Promise.all([
            X25519.scalarMult(serverEphemeral.privKey, clientEphemeralPub),
            X25519.scalarMult(serverEphemeral.privKey, clientStaticKey)
        ])
        handshake.mixIntoKey(dhEphem)
        handshake.mixIntoKey(dhStatic)
        const certChain = await buildFakeCertChain({
            root: this.config.rootCa,
            leafKey: this.config.serverStaticKeyPair.pubKey
        })
        const encryptedCertPayload = handshake.encrypt(certChain.encoded)

        const serverHello = proto.HandshakeMessage.encode({
            serverHello: {
                ephemeral: serverEphemeral.pubKey,
                payload: encryptedCertPayload
            }
        }).finish()

        this.frameSocket.sendFrame(serverHello)

        await this.completeAuthentication(handshake, clientPayload, clientStaticKey)
    }

    private async handleClientFinish(
        frame: Uint8Array,
        handshake: WaFakeNoiseHandshake,
        serverEphemeralKeyPair: SignalKeyPair
    ): Promise<void> {
        const parsed = proto.HandshakeMessage.decode(frame)
        const clientFinish = parsed.clientFinish
        if (!clientFinish?.static || !clientFinish.payload) {
            throw new Error('ClientFinish missing static/payload')
        }
        const clientStaticKey = handshake.decrypt(clientFinish.static)
        handshake.mixIntoKey(
            await X25519.scalarMult(serverEphemeralKeyPair.privKey, clientStaticKey)
        )
        const clientPayloadBytes = handshake.decrypt(clientFinish.payload)
        const clientPayload = parseClientPayload(clientPayloadBytes)

        await this.completeAuthentication(handshake, clientPayload, clientStaticKey)
    }

    private async completeAuthentication(
        handshake: WaFakeNoiseHandshake,
        clientPayload: ParsedClientPayload,
        clientStaticKey: Uint8Array
    ): Promise<void> {
        const keys = handshake.finish()
        const transport = new WaFakeTransport({
            recvKey: keys.recvKey,
            sendKey: keys.sendKey
        })
        this.state = { kind: 'authenticated', transport }
        this.authenticatedPayload = clientPayload

        await this.sendStanza(buildSuccessNode(this.config.successNodeAttributes))
        if (clientPayload.kind === 'login') {
            // Real WA drains offline messages after login and closes the
            // drain with this bulletin. Baileys-family clients buffer their
            // events until it arrives, so send it eagerly with count=0.
            await this.sendStanza({
                tag: 'ib',
                attrs: { from: 's.whatsapp.net' },
                content: [{ tag: 'offline', attrs: { count: '0' } }]
            })
        }
        this.events.onAuthenticated?.({ clientPayload, clientStaticKey })
    }

    private async handleAuthenticatedFrame(
        frame: Uint8Array,
        transport: WaFakeTransport
    ): Promise<void> {
        const stanzaBytes = await transport.decryptFrame(frame)
        const node = await decodeBinaryNodeStanza(stanzaBytes)
        this.events.onStanza?.(node)

        if (node.tag === 'iq') {
            const response = await this.config.routeIq(node)
            if (response !== null) {
                await this.sendStanza(response)
            } else {
                this.events.onUnhandledStanza?.(node)
            }
            return
        }

        // Mirror the minimal ack shape that resolves the lib pending publish.
        if (node.tag === 'message' && node.attrs.id) {
            const messageType = node.attrs.type ?? 'text'
            const from = node.attrs.to ?? 's.whatsapp.net'
            const ackAttrs: Record<string, string> = {
                id: node.attrs.id,
                class: 'receipt',
                type: messageType,
                from
            }
            if (node.attrs.participant) {
                ackAttrs.participant = node.attrs.participant
            }
            await this.sendStanza({
                tag: 'ack',
                attrs: ackAttrs
            })
        }
    }

    private fail(error: unknown): void {
        const err = error instanceof Error ? error : new Error(String(error))
        this.events.onError?.(err)
        this.state = { kind: 'closed' }
        this.config.connection.close(1011, err.message.slice(0, 120))
    }
}
