import type { GiftMessagePayload } from './types'
import { fetchStickerCatalog, isLottieJsonUrl, toAssetUrl } from '@/lib/stickers/catalog'

let catalogPromise: ReturnType<typeof fetchStickerCatalog> | null = null

function loadStickerCatalog() {
    if (!catalogPromise) {
        catalogPromise = fetchStickerCatalog()
    }
    return catalogPromise
}

/** 訊息 payload 已帶 lottieUrl 時可同步解析 */
export function getGiftLottieUrlSync(
    gift: Pick<GiftMessagePayload, 'lottieUrl'>
): string | null {
    if (isLottieJsonUrl(gift.lottieUrl)) {
        return toAssetUrl(gift.lottieUrl)
    }
    return null
}

/** 依 payload 或貼圖目錄（stickerName）解析 Lottie JSON 網址 */
export async function resolveGiftLottieUrl(
    gift: Pick<GiftMessagePayload, 'lottieUrl' | 'stickerName'>
): Promise<string | null> {
    const direct = getGiftLottieUrlSync(gift)
    if (direct) return direct

    const name = String(gift.stickerName ?? '').trim()
    if (!name) return null

    try {
        const catalog = await loadStickerCatalog()
        const item = catalog.stickerByName.get(name)
        if (item?.lottieUrl && isLottieJsonUrl(item.lottieUrl)) {
            return item.lottieUrl
        }
    } catch {
        return null
    }

    return null
}
