import type { WaAddonKind } from '@client/types'
import { aesGcmDecrypt, aesGcmEncrypt, sha256 } from '@crypto'
import {
    assertMessageSecret,
    createUseCaseSecret,
    WA_MESSAGE_SECRET_BYTES,
    WA_USE_CASE_SECRET_MODIFICATION_TYPES
} from '@message/crypto/use-case-secret'
import { unwrapMessage } from '@message/encode/content'
import { proto, type Proto } from '@proto'
import {
    isGroupOrBroadcastJid,
    isLidJid,
    isNewsletterJid,
    isUserJid,
    toUserJid
} from '@protocol/jid'
import type {
    WaMessageSecretEntry,
    WaMessageSecretStore
} from '@store/contracts/message-secret.store'
import type { WaMessageStore } from '@store/contracts/message.store'
import { bytesToHex, EMPTY_BYTES, TEXT_ENCODER, toBytesView } from '@util/bytes'
import { toError } from '@util/primitives'

const WA_ADDON_ENCRYPTION_NONCE_BYTES = 12

type WaAddonBytes = Uint8Array | ArrayBuffer | ArrayBufferView

type ModificationType =
    (typeof WA_USE_CASE_SECRET_MODIFICATION_TYPES)[keyof typeof WA_USE_CASE_SECRET_MODIFICATION_TYPES]

/** Returns `true` when an addon kind binds its AES-GCM ciphertext to additional data (polls + event responses). */
export function shouldUseAddonAdditionalData(modificationType: ModificationType): boolean {
    return (
        modificationType === WA_USE_CASE_SECRET_MODIFICATION_TYPES.POLL_VOTE ||
        modificationType === WA_USE_CASE_SECRET_MODIFICATION_TYPES.EVENT_RESPONSE
    )
}

/** Builds the canonical AES-GCM `additionalData` bytes for an addon (stanza id + NUL + sender). */
export function buildAddonAdditionalData(stanzaId: string, addOnSenderJid: string): Uint8Array {
    if (!stanzaId.trim()) {
        throw new Error('stanza id must be a non-empty string')
    }
    if (!addOnSenderJid.trim()) {
        throw new Error('addon sender jid must be a non-empty string')
    }
    return TEXT_ENCODER.encode(`${stanzaId}\u0000${addOnSenderJid}`)
}

/**
 * Deduplicates JID candidates as bare `user@server` (device stripped). Empty /
 * whitespace-only values are dropped. Order is preserved (first wins).
 */
export function collectUniqueUserJids(
    ...candidates: ReadonlyArray<string | null | undefined>
): readonly string[] {
    const out: string[] = []
    const seen = new Set<string>()
    for (const candidate of candidates) {
        if (typeof candidate !== 'string' || !candidate.trim()) continue
        let userJid: string
        try {
            userJid = toUserJid(candidate)
        } catch {
            continue
        }
        if (seen.has(userJid)) continue
        seen.add(userJid)
        out.push(userJid)
    }
    return out
}

/**
 * Resolves the parent-message author JID the peer used when encrypting an
 * addon (poll vote / event response / ...), or `null` when the key carries no
 * usable one. In a group the author is the key's `participant`; in 1:1 it is
 * `remoteJid`, which is how the sender addressed us (often our LID).
 *
 * A `fromMe` key is ours, so its author is this account and the stored parent
 * entry already holds that JID. `remoteJid` on such a key is the *chat*, i.e.
 * the other side, so reading it would seed the candidate list with the one
 * party that certainly did not write the parent.
 *
 * WhatsApp Web reads the author off its own stored parent message instead,
 * then normalizes the addressing mode. Taking it from the key the peer sent
 * is a shortcut to the same JID, in the exact form they encrypted with, so it
 * pairs with the stored author rather than replacing it.
 */
export function resolveAddonParentSenderFromKey(
    targetMessageKey: Proto.IMessageKey,
    chatIsGroup: boolean
): string | null {
    if (targetMessageKey.fromMe) return null
    const raw = chatIsGroup ? targetMessageKey.participant : targetMessageKey.remoteJid
    return collectUniqueUserJids(raw)[0] ?? null
}

export interface WaAddonSenderPair {
    readonly parentMsgOriginalSender: string
    readonly modificationSender: string
}

/**
 * Chat JIDs reach the candidate lists through stanza attributes (`from` and
 * the `*Alt` fields point at the group in a group chat) and can never be the
 * author of anything, so they are dropped. Everything else stays: the
 * as-received rung has to work for senders outside `@lid` / `@s.whatsapp.net`,
 * such as a hosted device.
 */
function isPossibleAddonSenderJid(jid: string): boolean {
    return !isGroupOrBroadcastJid(jid) && !isNewsletterJid(jid)
}

/** Builds the bounded LID, PN, and as-received sender rungs used by addon decryption. */
export function buildAddonSenderPairs(input: {
    readonly parentCandidates: readonly string[]
    readonly modificationCandidates: readonly string[]
}): readonly WaAddonSenderPair[] {
    const parents = input.parentCandidates.filter(isPossibleAddonSenderJid)
    const modifiers = input.modificationCandidates.filter(isPossibleAddonSenderJid)
    const pairs: WaAddonSenderPair[] = []
    const seen = new Set<string>()
    const addPair = (
        parentMsgOriginalSender: string | undefined,
        modificationSender: string | undefined
    ) => {
        if (!parentMsgOriginalSender || !modificationSender) return
        const key = `${parentMsgOriginalSender}\u0000${modificationSender}`
        if (seen.has(key)) return
        seen.add(key)
        pairs.push({ parentMsgOriginalSender, modificationSender })
    }

    addPair(
        parents.find((jid) => isLidJid(jid)),
        modifiers.find((jid) => isLidJid(jid))
    )
    addPair(
        parents.find((jid) => isUserJid(jid)),
        modifiers.find((jid) => isUserJid(jid))
    )
    addPair(parents[0], modifiers[0])
    return pairs
}

/**
 * Decrypts an addon payload, walking the sender rungs until one authenticates.
 * Needed during the PN→LID migration: the voter encrypts with the poll
 * creator's LID from `pollCreationMessageKey`, while we may have persisted the
 * secret under our PN `meJid`.
 *
 * Every attempt is local crypto over the same ciphertext, so a failed rung
 * says nothing beyond "wrong sender pair" and never aborts the walk. Only an
 * exhausted list throws, carrying the last error.
 */
export async function decryptAddonPayloadWithSenderFallback(input: {
    readonly messageSecret: WaAddonBytes
    readonly stanzaId: string
    readonly senderPairs: readonly WaAddonSenderPair[]
    readonly modificationType: ModificationType
    readonly ciphertext: WaAddonBytes
    readonly iv: WaAddonBytes
}): Promise<Uint8Array> {
    if (input.senderPairs.length === 0) {
        throw new Error('addon sender pairs must not be empty')
    }

    let lastError: unknown
    for (const { parentMsgOriginalSender, modificationSender } of input.senderPairs) {
        try {
            return await decryptAddonPayload({
                messageSecret: input.messageSecret,
                stanzaId: input.stanzaId,
                parentMsgOriginalSender,
                modificationSender,
                modificationType: input.modificationType,
                ciphertext: input.ciphertext,
                iv: input.iv,
                additionalData: shouldUseAddonAdditionalData(input.modificationType)
                    ? buildAddonAdditionalData(input.stanzaId, modificationSender)
                    : undefined
            })
        } catch (error) {
            lastError = error
        }
    }
    throw lastError instanceof Error ? lastError : new Error(toError(lastError).message)
}

/** Encrypts an addon payload (poll vote, reaction, edit, ...) with the per-use-case secret. */
export async function encryptAddonPayload(input: {
    readonly messageSecret: WaAddonBytes
    readonly stanzaId: string
    readonly parentMsgOriginalSender: string
    readonly modificationSender: string
    readonly modificationType: ModificationType
    readonly payload: WaAddonBytes
    readonly iv: WaAddonBytes
    readonly additionalData?: WaAddonBytes
}): Promise<Uint8Array> {
    const secret = await createUseCaseSecret({
        messageSecret: assertMessageSecret(input.messageSecret),
        stanzaId: input.stanzaId,
        parentMsgOriginalSender: input.parentMsgOriginalSender,
        modificationSender: input.modificationSender,
        modificationType: input.modificationType
    })
    const iv = assertAddonIv(input.iv)
    const additionalData = resolveAddonAdditionalData(input)
    return aesGcmEncrypt(secret, iv, toBytesView(input.payload), additionalData)
}

/** Decrypts an addon payload encrypted with {@link encryptAddonPayload}. */
export async function decryptAddonPayload(input: {
    readonly messageSecret: WaAddonBytes
    readonly stanzaId: string
    readonly parentMsgOriginalSender: string
    readonly modificationSender: string
    readonly modificationType: ModificationType
    readonly ciphertext: WaAddonBytes
    readonly iv: WaAddonBytes
    readonly additionalData?: WaAddonBytes
}): Promise<Uint8Array> {
    const secret = await createUseCaseSecret({
        messageSecret: assertMessageSecret(input.messageSecret),
        stanzaId: input.stanzaId,
        parentMsgOriginalSender: input.parentMsgOriginalSender,
        modificationSender: input.modificationSender,
        modificationType: input.modificationType
    })
    const iv = assertAddonIv(input.iv)
    const additionalData = resolveAddonAdditionalData(input)
    return aesGcmDecrypt(secret, iv, toBytesView(input.ciphertext), additionalData)
}

export interface WaIdentifiedEncAddon {
    readonly kind: WaAddonKind
    readonly targetMessageKey: Proto.IMessageKey
    readonly encPayload: Uint8Array
    readonly encIv: Uint8Array
    readonly modificationType: ModificationType
    readonly raw: Proto.IMessage
}

/**
 * Inspects a message and, when it contains an encrypted addon (reaction,
 * poll vote, edit, comment, event response, ...), returns the parsed
 * envelope with its kind and target message key. Returns `null` otherwise.
 */
export function identifyEncryptedAddon(message: Proto.IMessage): WaIdentifiedEncAddon | null {
    const msg = unwrapMessage(message)

    if (msg.encReactionMessage) {
        const { targetMessageKey, encPayload, encIv } = msg.encReactionMessage
        if (targetMessageKey && encPayload && encIv) {
            return {
                kind: 'reaction',
                targetMessageKey,
                encPayload: encPayload,
                encIv: encIv,
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.ENC_REACTION,
                raw: message
            }
        }
    }

    if (msg.pollUpdateMessage) {
        const { pollCreationMessageKey, vote } = msg.pollUpdateMessage
        if (pollCreationMessageKey && vote?.encPayload && vote.encIv) {
            return {
                kind: 'poll_vote',
                targetMessageKey: pollCreationMessageKey,
                encPayload: vote.encPayload,
                encIv: vote.encIv,
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.POLL_VOTE,
                raw: message
            }
        }
    }

    if (msg.encEventResponseMessage) {
        const { eventCreationMessageKey, encPayload, encIv } = msg.encEventResponseMessage
        if (eventCreationMessageKey && encPayload && encIv) {
            return {
                kind: 'event_response',
                targetMessageKey: eventCreationMessageKey,
                encPayload: encPayload,
                encIv: encIv,
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.EVENT_RESPONSE,
                raw: message
            }
        }
    }

    if (msg.encCommentMessage) {
        const { targetMessageKey, encPayload, encIv } = msg.encCommentMessage
        if (targetMessageKey && encPayload && encIv) {
            return {
                kind: 'comment',
                targetMessageKey,
                encPayload: encPayload,
                encIv: encIv,
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.ENC_COMMENT,
                raw: message
            }
        }
    }

    if (msg.secretEncryptedMessage) {
        const { targetMessageKey, encPayload, encIv, secretEncType } = msg.secretEncryptedMessage
        if (
            targetMessageKey?.id &&
            encPayload &&
            encIv &&
            encIv.byteLength === WA_ADDON_ENCRYPTION_NONCE_BYTES
        ) {
            const mapped = mapSecretEncType(secretEncType)
            if (mapped) {
                return {
                    kind: mapped.kind,
                    targetMessageKey,
                    encPayload,
                    encIv,
                    modificationType: mapped.modificationType,
                    raw: message
                }
            }
        }
    }

    return null
}

function mapSecretEncType(
    secretEncType: Proto.Message.SecretEncryptedMessage.SecretEncType | null | undefined
): { kind: WaAddonKind; modificationType: ModificationType } | null {
    switch (secretEncType) {
        case proto.Message.SecretEncryptedMessage.SecretEncType.MESSAGE_EDIT:
            return {
                kind: 'message_edit',
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.MESSAGE_EDIT
            }
        case proto.Message.SecretEncryptedMessage.SecretEncType.EVENT_EDIT:
            return {
                kind: 'event_edit',
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.EVENT_EDIT_ENCRYPTED
            }
        case proto.Message.SecretEncryptedMessage.SecretEncType.POLL_EDIT:
            return {
                kind: 'poll_edit',
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.POLL_EDIT_ENCRYPTED
            }
        case proto.Message.SecretEncryptedMessage.SecretEncType.POLL_ADD_OPTION:
            return {
                kind: 'poll_add_option',
                modificationType: WA_USE_CASE_SECRET_MODIFICATION_TYPES.POLL_ADD_OPTION
            }
        default:
            return null
    }
}

export type WaDecodedAddon =
    | { readonly kind: 'reaction'; readonly reaction: Proto.Message.IReactionMessage }
    | {
          readonly kind: 'poll_vote'
          readonly pollVote: Proto.Message.IPollVoteMessage
          readonly selectedOptionNames: readonly string[] | null
      }
    | {
          readonly kind: 'event_response'
          readonly eventResponse: Proto.Message.IEventResponseMessage
      }
    | { readonly kind: 'comment'; readonly comment: Proto.Message.ICommentMessage }
    | { readonly kind: 'message_edit'; readonly message: Proto.IMessage }
    | { readonly kind: 'event_edit'; readonly message: Proto.IMessage }
    | { readonly kind: 'poll_edit'; readonly message: Proto.IMessage }
    | { readonly kind: 'poll_add_option'; readonly message: Proto.IMessage }

/** Decodes the decrypted addon plaintext into its typed protobuf message based on `kind`. */
export function decodeAddonPlaintext(kind: WaAddonKind, plaintext: Uint8Array): WaDecodedAddon {
    switch (kind) {
        case 'reaction':
            return { kind, reaction: proto.Message.ReactionMessage.decode(plaintext) }
        case 'poll_vote':
            return {
                kind,
                pollVote: proto.Message.PollVoteMessage.decode(plaintext),
                selectedOptionNames: null
            }
        case 'event_response':
            return { kind, eventResponse: proto.Message.EventResponseMessage.decode(plaintext) }
        case 'comment':
            return { kind, comment: proto.Message.CommentMessage.decode(plaintext) }
        case 'message_edit':
        case 'event_edit':
        case 'poll_edit':
        case 'poll_add_option':
            return { kind, message: proto.Message.decode(plaintext) }
    }
}

export async function resolveParentMessageSecret(
    targetMessageId: string,
    messageSecretStore: WaMessageSecretStore,
    messageStore: WaMessageStore
): Promise<WaMessageSecretEntry | null> {
    const cached = await messageSecretStore.get(targetMessageId)
    if (cached) return cached

    const record = await messageStore.getById(targetMessageId)
    if (!record?.messageBytes) return null

    try {
        const decoded = proto.Message.decode(record.messageBytes)
        const secret = decoded.messageContextInfo?.messageSecret
        if (!secret || secret.byteLength !== WA_MESSAGE_SECRET_BYTES) return null
        return { secret, senderJid: record.senderJid ?? '' }
    } catch {
        return null
    }
}

export async function resolvePollOptionNames(
    selectedOptions: readonly Uint8Array[],
    pollCreationMessageId: string,
    messageStore: WaMessageStore
): Promise<readonly string[] | null> {
    const record = await messageStore.getById(pollCreationMessageId)
    if (!record?.messageBytes) return null

    let decoded: ReturnType<typeof proto.Message.decode>
    try {
        decoded = proto.Message.decode(record.messageBytes)
    } catch {
        return null
    }
    const pollMsg = unwrapMessage(decoded)
    const options =
        pollMsg.pollCreationMessage?.options ??
        pollMsg.pollCreationMessageV2?.options ??
        pollMsg.pollCreationMessageV3?.options ??
        pollMsg.pollCreationMessageV5?.options
    if (!options || options.length === 0) return null

    const hashToName = new Map<string, string>()
    for (const option of options) {
        if (!option.optionName) continue
        const hash = sha256(TEXT_ENCODER.encode(option.optionName))
        hashToName.set(bytesToHex(hash), option.optionName)
    }

    const names: string[] = []
    for (const selected of selectedOptions) {
        const hex = bytesToHex(selected)
        const name = hashToName.get(hex)
        if (!name) return null
        names.push(name)
    }
    return names
}

function assertAddonIv(iv: WaAddonBytes): Uint8Array {
    const normalized = toBytesView(iv)
    if (normalized.byteLength !== WA_ADDON_ENCRYPTION_NONCE_BYTES) {
        throw new Error(
            `addon iv must be ${WA_ADDON_ENCRYPTION_NONCE_BYTES} bytes (got ${normalized.byteLength})`
        )
    }
    return normalized
}

function resolveAddonAdditionalData(input: {
    readonly stanzaId: string
    readonly modificationSender: string
    readonly modificationType: ModificationType
    readonly additionalData?: WaAddonBytes
}): Uint8Array {
    if (input.additionalData) {
        return toBytesView(input.additionalData)
    }
    if (!shouldUseAddonAdditionalData(input.modificationType)) {
        return EMPTY_BYTES
    }
    return buildAddonAdditionalData(input.stanzaId, input.modificationSender)
}
