import type { ChatMessage } from '@/app/room/_components/types'
import type { GiftMessagePayload, SendGiftWsPayload } from './types'

export const GIFT_SEND_COUNT_MAX = 9999

export function clampGiftSendCount(count: number): number {
    const n = Math.floor(Number(count) || 0)
    if (n <= 0) return 0
    return Math.min(GIFT_SEND_COUNT_MAX, n)
}

export function buildSendGiftWsPayload(params: {
    stickerName: string
    recipientUserId: string
    count: number
}): SendGiftWsPayload {
    return {
        type: 'send_gift',
        stickerName: params.stickerName,
        recipientUserId: params.recipientUserId,
        count: clampGiftSendCount(params.count) || 1,
    }
}

type WsGiftMessageData = {
    id: string
    userId?: string | null
    author?: string
    userType?: ChatMessage['userType']
    createdAtMs?: number
    authorPublicPathKey?: string
    gift?: GiftMessagePayload
}

export function wsGiftDataToChatMessage(
    data: WsGiftMessageData,
    resolveUserType?: (userId: string | null | undefined) => ChatMessage['userType'] | undefined,
): ChatMessage | null {
    if (!data?.id || !data.gift) return null

    const userId = data.userId ?? null
    const userType = data.userType ?? resolveUserType?.(userId)

    return {
        id: data.id,
        author: data.author || '',
        text: '',
        userId,
        userType,
        time: data.createdAtMs
            ? new Date(data.createdAtMs).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
            : undefined,
        authorPublicPathKey:
            typeof data.authorPublicPathKey === 'string' && data.authorPublicPathKey.trim()
                ? data.authorPublicPathKey.trim()
                : undefined,
        gift: data.gift,
    }
}

export function appendGiftChatMessage(
    prev: ChatMessage[],
    message: ChatMessage,
): ChatMessage[] {
    if (prev.some((m) => m.id === message.id)) return prev
    return [...prev, message]
}
