import { loadOrCreateCredentials, persistCredentials } from '../credentials-flow'
import type { WaAuthCredentials, WaMobileTransportDeviceInfo } from '../types'
import { randomBytesAsync } from '../../crypto'
import { bytesToBase64, bytesToBase64UrlSafe, intToBytes } from '../../util/bytes'
import { randomUUID } from 'node:crypto'
import { calculateRegistrationToken, generateRequestToken } from './token'
import { buildEncryptedRegistrationBody } from './enc'
import type {
    HttpRegistrationFlow,
    RegisteredMobilePrimary,
    RegisterOptions,
    RegisterResult,
    RequestCodeOptions,
    RequestCodeResult,
    WaHttpRegistrationFlowDeps
} from './types'

const DEFAULT_BASE_URL = 'https://v.whatsapp.net'
// Current store builds (whalibmob 5.33.23, 2026). A version the server does not
// know for the announced platform is answered with `old_version`.
const DEFAULT_APP_VERSION = '2.26.41.78'
const IOS_DEFAULT_APP_VERSION = '2.26.41.74'
const DEFAULT_DEVICE_INFO: WaMobileTransportDeviceInfo = {
    os: 'android',
    manufacturer: 'Google',
    // Android `device` is a build codename (e.g. `panther` for a Pixel 7),
    // never a marketing name – the user agent is built as `Google-panther`.
    device: 'panther',
    osVersion: '14',
    osBuildNumber: 'UQ1A.240205.004',
    appVersion: DEFAULT_APP_VERSION,
    mcc: '000',
    mnc: '000',
    localeLanguageIso6391: 'en',
    localeCountryIso31661Alpha2: 'US'
}
const DEFAULT_IOS_DEVICE_INFO: WaMobileTransportDeviceInfo = {
    os: 'ios',
    manufacturer: 'Apple',
    device: 'iPhone 15 Pro',
    osVersion: '17.4.1',
    osBuildNumber: '21E236',
    appVersion: IOS_DEFAULT_APP_VERSION,
    deviceModelType: 'iPhone16,1',
    distributionChannel: 'appstore',
    localeLanguageIso6391: 'en',
    localeCountryIso31661Alpha2: 'US'
}
/** Byte length of the per-request `expid` (experiment id). */
const EXP_ID_LENGTH = 16
/** Byte length of the per-request `id` (device identity blob). */
const REQUEST_ID_LENGTH = 20
/** Fallback mobile network codes for devices without a SIM. */
const DEFAULT_MCC = '000'
const DEFAULT_MNC = '000'

/**
 * Native form builder: name=value joined with `&`, values already in their
 * wire form. Using URLSearchParams here would double-encode `id` (`%AA` →
 * `%25AA`) and the percent-encoded Android token.
 */
class RegistrationForm {
    private readonly parts: string[] = []

    append(name: string, value: string | number | undefined | null, raw = false): this {
        if (value === undefined || value === null) return this
        this.parts.push(`${name}=${raw ? String(value) : encodeURIComponent(String(value))}`)
        return this
    }

    toString(): string {
        return this.parts.join('&')
    }
}

export class WaHttpRegistrationFlow implements HttpRegistrationFlow {
    private readonly logger: WaHttpRegistrationFlowDeps['logger']
    private readonly authStore: WaHttpRegistrationFlowDeps['authStore']
    private readonly signalStore: WaHttpRegistrationFlowDeps['signalStore']
    private readonly preKeyStore: WaHttpRegistrationFlowDeps['preKeyStore']
    private readonly fetchImpl: typeof fetch
    private readonly baseUrl: string
    private readonly androidApkMaterial?: WaHttpRegistrationFlowDeps['androidApkMaterial']
    private readonly registrationPublicKey?: Uint8Array
    private readonly tokenStatic?: string
    private credentials?: WaAuthCredentials
    private deviceInfo?: WaMobileTransportDeviceInfo
    /** 16 random bytes, base64url, stable for the lifetime of the flow. */
    private accessSessionId?: string

    constructor(deps: WaHttpRegistrationFlowDeps) {
        this.logger = deps.logger
        this.authStore = deps.authStore
        this.signalStore = deps.signalStore
        this.preKeyStore = deps.preKeyStore
        this.fetchImpl = deps.fetch ?? globalThis.fetch
        this.baseUrl = deps.baseUrl ?? DEFAULT_BASE_URL
        this.androidApkMaterial = deps.androidApkMaterial
        this.registrationPublicKey = deps.registrationPublicKey
        this.tokenStatic = deps.tokenStatic
    }

    async loadOrCreateKeys(): Promise<WaAuthCredentials> {
        this.logger.debug('Loading or creating credentials for HTTP registration')
        this.credentials = await loadOrCreateCredentials({
            logger: this.logger,
            authStore: this.authStore,
            signalStore: this.signalStore,
            preKeyStore: this.preKeyStore,
            skipSignedPreKeySignatureVerification: true
        })
        return this.credentials
    }

    private ensureCredentials(): WaAuthCredentials {
        if (!this.credentials) {
            throw new Error('Credentials not loaded. Call loadOrCreateKeys() first.')
        }
        return this.credentials
    }

    private buildDeviceInfo(
        options: RequestCodeOptions | RegisterOptions
    ): WaMobileTransportDeviceInfo {
        if (!this.deviceInfo) {
            const platformDefaults =
                options.deviceInfo?.os === 'ios' ? DEFAULT_IOS_DEVICE_INFO : DEFAULT_DEVICE_INFO
            const merged: WaMobileTransportDeviceInfo = {
                ...platformDefaults,
                ...(options.deviceInfo ?? {}),
                os: options.deviceInfo?.os ?? platformDefaults.os,
                appVersion: options.deviceInfo?.appVersion ?? platformDefaults.appVersion,
                phoneId: options.deviceInfo?.phoneId ?? randomUUID()
            }
            // The Android token is signed over a specific APK's classes.dex. The
            // announced version has to be that APK's version, not the store's.
            const materialVersion = this.androidApkMaterial?.apkVersion
            this.deviceInfo =
                merged.os === 'android' && materialVersion
                    ? { ...merged, appVersion: materialVersion }
                    : merged
        } else if (options.deviceInfo) {
            this.deviceInfo = { ...this.deviceInfo, ...options.deviceInfo }
        }
        return this.deviceInfo
    }

    /**
     * Parameters shared by every endpoint of the HTTP registration flow: the
     * country/number pair, the key material that proves device ownership and
     * the per-request identity triple (`expid` / `id` / `fdid`).
     *
     * `expid` and `id` are fresh for every request; `fdid` is the stable
     * per-device UUID that ties the requests of one registration attempt
     * together.
     */
    private async buildIdentityParams(
        options: RequestCodeOptions | RegisterOptions
    ): Promise<RegistrationForm> {
        const creds = this.ensureCredentials()
        const deviceInfo = this.buildDeviceInfo(options)

        const params = new RegistrationForm()
        params.append('cc', options.cc)
        params.append('in', options.in)
        if (options.lg) params.append('lg', options.lg)
        if (options.lc) params.append('lc', options.lc)

        // Key material from credentials. Native clients send URL-safe base64
        // with the Java padding (`=`), not standard base64's `+` and `/`.
        params.append(
            'e_regid',
            bytesToBase64Url(intToBytes(4, creds.registrationInfo.registrationId))
        )
        params.append('e_keytype', bytesToBase64Url(new Uint8Array([5]))) // BQ
        params.append(
            'e_ident',
            bytesToBase64Url(stripKeyPrefix(creds.registrationInfo.identityKeyPair.pubKey))
        )

        // authkey from noiseKeyPair
        params.append('authkey', bytesToBase64Url(stripKeyPrefix(creds.noiseKeyPair.pubKey)))

        // Device identity triple. The native clients differ on casing: Android
        // lowercases the UUID, iOS uppercases it.
        const fdid = deviceInfo.phoneId ?? randomUUID()
        params.append('fdid', deviceInfo.os === 'ios' ? fdid.toUpperCase() : fdid.toLowerCase())
        params.append('expid', bytesToBase64Url(await randomBytesAsync(EXP_ID_LENGTH)))
        // `id` is not base64: the native client sends it as %XX hex. Marked raw
        // so it is not double-encoded.
        params.append('id', bytesToUrlHex(await randomBytesAsync(REQUEST_ID_LENGTH)), true)
        params.append('access_session_id', await this.getAccessSessionId())
        params.append('type', '0')
        params.append('t', String(Math.floor(Date.now() / 1000)))
        params.append('reg_client_event_ts', String(Date.now()))
        params.append('ios_id', bytesToBase64Url(new TextEncoder().encode(fdid.replace(/-/g, '').slice(0, 16))))

        return params
    }

    private async getAccessSessionId(): Promise<string> {
        if (!this.accessSessionId) {
            this.accessSessionId = bytesToBase64UrlSafe(await randomBytesAsync(16))
        }
        return this.accessSessionId
    }

    /**
     * Full parameter set for the code-request and register endpoints.
     * The native client also sends `token` on /v2/exist; the server rejects
     * the probe with `incorrect` without it.
     */
    private async buildRegistrationParams(
        options: RequestCodeOptions | RegisterOptions,
        includeCode?: string,
        useToken = true
    ): Promise<RegistrationForm> {
        const creds = this.ensureCredentials()
        const deviceInfo = this.buildDeviceInfo(options)

        const params = await this.buildIdentityParams(options)

        // Signed pre-key – every endpoint carries it.
        params.append('e_skey_id', bytesToBase64Url(intToBytes(3, creds.signedPreKey.keyId)))
        params.append(
            'e_skey_val',
            bytesToBase64Url(stripKeyPrefix(creds.signedPreKey.keyPair.pubKey))
        )
        params.append('e_skey_sig', bytesToBase64Url(creds.signedPreKey.signature))

        // Network/sim info
        params.append('mcc', deviceInfo.mcc ?? options.simMcc ?? DEFAULT_MCC)
        params.append('mnc', deviceInfo.mnc ?? options.simMnc ?? DEFAULT_MNC)
        if (options.simMcc) params.append('sim_mcc', options.simMcc)
        if (options.simMnc) params.append('sim_mnc', options.simMnc)

        // Other params
        params.append('pid', '9634')
        params.append('rc', '0')
        params.append('client_metrics', JSON.stringify({ attempts: 1 }))
        params.append('hasav', '2')
        params.append('network_radio_type', '1')
        params.append('simnum', '1')
        params.append('hasinrc', '1')

        // Token: national number only (NO country code), platform-correct.
        if (useToken) {
            const token = calculateRegistrationToken(
                deviceInfo.appVersion ?? DEFAULT_APP_VERSION,
                options.in,
                {
                    os: deviceInfo.os === 'ios' ? 'ios' : 'android',
                    business: deviceInfo.business,
                    staticToken: this.tokenStatic,
                    androidMaterial: this.androidApkMaterial
                }
            )
            // iOS token is hex. The Android token is already percent-encoded
            // base64, so keep it raw.
            params.append('token', token, true)
        }

        if (includeCode !== undefined) {
            params.append('code', includeCode)
            const enteredMethod = (options as RegisterOptions).method
            const entered =
                enteredMethod === 'voice' || enteredMethod === 'wa_old' ? '1' : '2'
            params.append('entered', entered)
        }

        const method = (options as RequestCodeOptions).method
        if (method) {
            params.append('method', method)
        }

        const reason = (options as RequestCodeOptions).reason
        if (reason) {
            params.append('reason', reason)
        }

        return params
    }

    private async buildHeaders(): Promise<Record<string, string>> {
        const deviceInfo = this.deviceInfo ?? DEFAULT_DEVICE_INFO
        const appVersion = deviceInfo.appVersion ?? DEFAULT_APP_VERSION
        const os = deviceInfo.os === 'ios' ? 'ios' : 'android'
        const ua =
            os === 'ios'
                ? `WhatsApp/${appVersion} iOS/${deviceInfo.osVersion ?? '17.4.1'} Device/${deviceInfo.device ?? 'iPhone 15 Pro'}`
                : `WhatsApp/${appVersion} Android/${deviceInfo.osVersion ?? '14'} Device/${deviceInfo.manufacturer ?? 'Google'}-${deviceInfo.device ?? 'panther'}`
        const headers: Record<string, string> = {
            'User-Agent': ua,
            Accept: 'text/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        }
        // The Android native client sends these; iOS does not.
        if (os !== 'ios') {
            headers.WaMsysRequest = '1'
            headers.request_token = await generateRequestToken()
        }
        return headers
    }

    private async postEncrypted(
        path: string,
        options: RequestCodeOptions | RegisterOptions,
        includeCode?: string,
        useToken = true
    ): Promise<Response> {
        const params = await this.buildRegistrationParams(options, includeCode, useToken)
        const headers = await this.buildHeaders()
        const body = await buildEncryptedRegistrationBody(params.toString(), {
            serverPublicKey: this.registrationPublicKey
        })
        return this.fetchImpl(`${this.baseUrl}${path}`, {
            method: 'POST',
            headers,
            body
        })
    }

    async checkExist(options: RequestCodeOptions): Promise<unknown> {
        this.logger.debug('Checking if number exists via v2/exist')
        const res = await this.postEncrypted('/v2/exist', options, undefined, true)
        const text = await res.text()
        try {
            return JSON.parse(text)
        } catch {
            return { raw: text }
        }
    }

    async requestCode(options: RequestCodeOptions): Promise<RequestCodeResult> {
        this.logger.info('Requesting registration code', {
            cc: options.cc,
            in: '***',
            method: options.method ?? 'sms'
        })

        const res = await this.postEncrypted('/v2/code', {
            ...options,
            method: options.method ?? 'sms'
        })
        const text = await res.text()
        this.logger.debug('v2/code response', { status: res.status })
        try {
            const json = JSON.parse(text)
            if (json.status === 'sent') {
                return { status: 'sent', length: json.length, retry_after: json.retry_after, raw: json }
            }
            return { status: 'fail', reason: json.reason, raw: json }
        } catch {
            return { status: 'fail', reason: text, raw: text }
        }
    }

    async register(options: RegisterOptions): Promise<RegisterResult> {
        this.logger.info('Registering with code', { cc: options.cc, in: '***' })

        const res = await this.postEncrypted('/v2/register', options, options.code)
        const text = await res.text()
        this.logger.debug('v2/register response', { status: res.status })
        try {
            const json = JSON.parse(text)
            if (json.status === 'ok') {
                return { status: 'ok', login: json.login, pw: json.pw, type: json.type, raw: json }
            }
            return { status: 'fail', reason: json.reason, raw: json }
        } catch {
            return { status: 'fail', reason: text, raw: text }
        }
    }

    async registerPhone(
        options: RequestCodeOptions & { code: string }
    ): Promise<RegisteredMobilePrimary> {
        const creds = this.ensureCredentials()
        const login = options.cc + options.in
        const meJid = `${login}@s.whatsapp.net`
        const deviceInfo = this.buildDeviceInfo(options)

        // Perform registration
        const result = await this.register({ ...options, code: options.code })
        if (result.status !== 'ok') {
            throw new Error(
                `Registration failed: ${result.reason} ${JSON.stringify(result.raw)}`
            )
        }

        // Set meJid and persist
        const pushName = options.pushName
        const updated: WaAuthCredentials = {
            ...creds,
            meJid: result.login ? `${result.login}@s.whatsapp.net` : meJid,
            deviceInfo,
            ...(pushName !== undefined ? { pushName } : {})
        }
        await persistCredentials(
            {
                logger: this.logger,
                authStore: this.authStore,
                signalStore: this.signalStore,
                preKeyStore: this.preKeyStore
            },
            updated
        )
        this.credentials = updated

        this.logger.info('Registration complete, credentials persisted as mobile primary', {
            meJid: updated.meJid
        })

        return {
            meJid: updated.meJid ?? meJid,
            login,
            credentials: updated,
            deviceInfo
        }
    }
}

/** URL-safe base64 WITH padding, matching Java's Base64.getUrlEncoder(). */
function bytesToBase64Url(value: Uint8Array): string {
    return bytesToBase64(value).replace(/\+/g, '-').replace(/\//g, '_')
}

function stripKeyPrefix(key: Uint8Array): Uint8Array {
    return key.length === 33 && key[0] === 0x05 ? key.subarray(1) : key
}

function bytesToUrlHex(value: Uint8Array): string {
    let out = ''
    for (let i = 0; i < value.length; i += 1) {
        out += `%${value[i].toString(16).toUpperCase().padStart(2, '0')}`
    }
    return out
}

export function createHttpRegistrationFlow(deps: WaHttpRegistrationFlowDeps): HttpRegistrationFlow {
    return new WaHttpRegistrationFlow(deps)
}
