import type { GiftMessagePayload } from './types'

/** 同一次連續送禮（多個數量）在此時間內只播一次 Lottie */
export const GIFT_LOTTIE_BATCH_WINDOW_MS = 2500

export function buildGiftLottieBatchKey(
    gift: Pick<GiftMessagePayload, 'stickerName' | 'recipientUserId'>,
    senderUserId: string | null | undefined
): string {
    const sender = String(senderUserId ?? '').trim()
    const recipient = String(gift.recipientUserId ?? '').trim()
    const sticker = String(gift.stickerName ?? '').trim()
    return `${sender}|${recipient}|${sticker}`
}

export type GiftLottieDedupeState = {
    messageIds: Set<string>
    batchUntil: Map<string, number>
}

export function createGiftLottieDedupeState(): GiftLottieDedupeState {
    return {
        messageIds: new Set(),
        batchUntil: new Map(),
    }
}

export function shouldEnqueueGiftLottie(
    state: GiftLottieDedupeState,
    messageId: string,
    batchKey: string,
    nowMs: number = Date.now()
): boolean {
    const id = String(messageId ?? '').trim()
    if (!id) return false
    if (state.messageIds.has(id)) return false

    const batchUntil = state.batchUntil.get(batchKey)
    if (batchUntil != null && nowMs < batchUntil) return false

    state.messageIds.add(id)
    state.batchUntil.set(batchKey, nowMs + GIFT_LOTTIE_BATCH_WINDOW_MS)

    if (state.messageIds.size > 200) {
        state.messageIds.clear()
    }
    if (state.batchUntil.size > 100) {
        const cutoff = nowMs - GIFT_LOTTIE_BATCH_WINDOW_MS
        for (const [key, until] of state.batchUntil) {
            if (until < cutoff) state.batchUntil.delete(key)
        }
    }

    return true
}
