// riyoo.js — ESM adapter untuk tipe pesan khusus di baileys-yorkv2
// sumber dri kiuurr

import { randomBytes } from 'crypto';
import { proto } from '../../WAProto/index.js';
import {
    generateWAMessage,
    generateWAMessageFromContent,
    generateWAMessageContent,
    generateMessageIDV2,
    prepareWAMessageMedia
} from '../Utils/index.js';

export class Riyoo {
    constructor(waUploadToServer, relayMessageFn, meId, logger) {
        this.waUploadToServer = waUploadToServer;
        this.relayMessage = relayMessageFn;
        this.meId = meId;
        this.logger = logger;
    }

    detectType(content) {
        if (content.requestPaymentMessage) return 'PAYMENT';
        if (content.productMessage)        return 'PRODUCT';
        if (content.interactiveMessage)    return 'INTERACTIVE';
        if (content.albumMessage)          return 'ALBUM';
        if (content.eventMessage)          return 'EVENT';
        if (content.pollResultMessage)     return 'POLL_RESULT';
        if (content.groupStatusMessage)    return 'GROUP_STORY';
        return null;
    }

    async handlePayment(content, quoted) {
        const data = content.requestPaymentMessage;
        let notes = {};

        if (data.sticker?.stickerMessage) {
            notes = {
                stickerMessage: {
                    ...data.sticker.stickerMessage,
                    contextInfo: {
                        stanzaId: quoted?.key?.id,
                        participant: quoted?.key?.participant || content.sender,
                        quotedMessage: quoted?.message
                    }
                }
            };
        } else if (data.note) {
            notes = {
                extendedTextMessage: {
                    text: data.note,
                    contextInfo: {
                        stanzaId: quoted?.key?.id,
                        participant: quoted?.key?.participant || content.sender,
                        quotedMessage: quoted?.message
                    }
                }
            };
        }

        return {
            requestPaymentMessage: proto.Message.RequestPaymentMessage.fromObject({
                expiryTimestamp: data.expiry || 0,
                amount1000: data.amount || 0,
                currencyCodeIso4217: data.currency || 'IDR',
                requestFrom: data.from || '0@s.whatsapp.net',
                noteMessage: notes,
                background: data.background ?? {
                    id: 'DEFAULT',
                    placeholderArgb: 0xFFF0F0F0
                }
            })
        };
    }

    async handleProduct(content, jid, quoted) {
        const {
            title,
            description,
            thumbnail,
            productId,
            retailerId,
            url,
            body = '',
            footer = '',
            buttons = [],
            priceAmount1000 = null,
            currencyCode = 'IDR'
        } = content.productMessage;

        let productImage;

        if (Buffer.isBuffer(thumbnail)) {
            const { imageMessage } = await generateWAMessageContent(
                { image: thumbnail },
                { upload: this.waUploadToServer }
            );
            productImage = imageMessage;
        } else if (typeof thumbnail === 'object' && thumbnail?.url) {
            const { imageMessage } = await generateWAMessageContent(
                { image: { url: thumbnail.url } },
                { upload: this.waUploadToServer }
            );
            productImage = imageMessage;
        }

        return {
            viewOnceMessage: {
                message: {
                    interactiveMessage: {
                        body: { text: body },
                        footer: { text: footer },
                        header: {
                            title,
                            hasMediaAttachment: true,
                            productMessage: {
                                product: {
                                    productImage,
                                    productId,
                                    title,
                                    description,
                                    currencyCode,
                                    priceAmount1000,
                                    retailerId,
                                    url,
                                    productImageCount: 1
                                },
                                businessOwnerJid: '0@s.whatsapp.net'
                            }
                        },
                        nativeFlowMessage: { buttons }
                    }
                }
            }
        };
    }

    async handleInteractive(content, jid, quoted) {
        const {
            title,
            footer,
            thumbnail,
            image,
            video,
            document,
            mimetype,
            fileName,
            jpegThumbnail,
            contextInfo,
            externalAdReply,
            buttons = [],
            nativeFlowMessage,
            header
        } = content.interactiveMessage;

        let media = null;
        let mediaType = null;

        if (thumbnail) {
            // support string URL, Buffer, or { url } object
            let thumbPayload;
            if (Buffer.isBuffer(thumbnail)) {
                thumbPayload = { image: thumbnail };
            } else if (typeof thumbnail === 'string') {
                thumbPayload = { image: { url: thumbnail } };
            } else if (typeof thumbnail === 'object' && thumbnail?.url) {
                thumbPayload = { image: { url: thumbnail.url } };
            } else {
                thumbPayload = { image: thumbnail };
            }
            media = await prepareWAMessageMedia(thumbPayload, { upload: this.waUploadToServer });
            mediaType = 'image';
        } else if (image) {
            media = await prepareWAMessageMedia(
                { image: typeof image === 'object' && image.url ? { url: image.url } : image },
                { upload: this.waUploadToServer }
            );
            mediaType = 'image';
        } else if (video) {
            media = await prepareWAMessageMedia(
                { video: typeof video === 'object' && video.url ? { url: video.url } : video },
                { upload: this.waUploadToServer }
            );
            mediaType = 'video';
        } else if (document) {
            const docPayload = { document };
            if (jpegThumbnail) {
                docPayload.jpegThumbnail = typeof jpegThumbnail === 'object' && jpegThumbnail.url
                    ? { url: jpegThumbnail.url }
                    : jpegThumbnail;
            }
            media = await prepareWAMessageMedia(docPayload, { upload: this.waUploadToServer });
            if (fileName)  media.documentMessage.fileName = fileName;
            if (mimetype)  media.documentMessage.mimetype = mimetype;
            mediaType = 'document';
        }

        const interactiveMsg = {
            body:   { text: title  || '' },
            footer: { text: footer || '' }
        };

        // Resolve buttons: prefer nativeFlowMessage.buttons if present, fallback to top-level buttons
        const resolvedButtons = (nativeFlowMessage?.buttons?.length > 0)
            ? nativeFlowMessage.buttons
            : (buttons?.length > 0 ? buttons : []);

        if (nativeFlowMessage) {
            // Preserve full nativeFlowMessage (including messageParamsJson) and override buttons
            interactiveMsg.nativeFlowMessage = {
                ...nativeFlowMessage,
                buttons: resolvedButtons
            };
        } else if (resolvedButtons.length > 0) {
            interactiveMsg.nativeFlowMessage = { buttons: resolvedButtons };
        }

        interactiveMsg.header = media
            ? { title: header || '', hasMediaAttachment: true, ...media }
            : { title: header || '', hasMediaAttachment: false };

        const finalContextInfo = { ...(contextInfo || {}) };
        if (externalAdReply) {
            finalContextInfo.externalAdReply = {
                title: '',
                body: '',
                mediaType: 1,
                thumbnailUrl: '',
                mediaUrl: '',
                sourceUrl: '',
                showAdAttribution: false,
                renderLargerThumbnail: false,
                ...externalAdReply
            };
        }

        if (Object.keys(finalContextInfo).length > 0) {
            interactiveMsg.contextInfo = finalContextInfo;
        }

        const msg = await generateWAMessageFromContent(jid, {
            interactiveMessage: interactiveMsg
        }, {
            userJid: this.meId,
            quoted,
            messageId: generateMessageIDV2(this.meId)
        });

        await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
        return msg;
    }

    async handleAlbum(content, jid, quoted) {
        const array = content.albumMessage;
        const userJid = this.meId;

        const album = await generateWAMessageFromContent(jid, {
            messageContextInfo: {
                messageSecret: randomBytes(32)
            },
            albumMessage: {
                expectedImageCount: array.filter(a => 'image' in a).length,
                expectedVideoCount: array.filter(a => 'video' in a).length
            }
        }, {
            userJid,
            quoted,
            upload: this.waUploadToServer
        });

        await this.relayMessage(jid, album.message, { messageId: album.key.id });

        for (const item of array) {
            const img = await generateWAMessage(jid, item, {
                upload: this.waUploadToServer,
                messageId: generateMessageIDV2(userJid)
            });

            img.message.messageContextInfo = {
                messageSecret: randomBytes(32),
                messageAssociation: {
                    associationType: 1,
                    parentMessageKey: album.key
                },
                participant: '0@s.whatsapp.net',
                remoteJid: 'status@broadcast',
                forwardingScore: 99999,
                isForwarded: true,
                mentionedJid: [jid],
                starred: true,
                labels: ['Y', 'Important'],
                isHighlighted: true,
                businessMessageForwardInfo: { businessOwnerJid: jid },
                dataSharingContext: { showMmDisclosure: true }
            };

            img.message.forwardedNewsletterMessageInfo = {
                newsletterJid: '0@newsletter',
                serverMessageId: 1,
                newsletterName: 'WhatsApp',
                contentType: 1,
                timestamp: new Date().toISOString(),
                senderName: 'kikyy dugonggg',
                content: 'Text Message',
                priority: 'high',
                status: 'sent'
            };

            img.message.disappearingMode = {
                initiator: 3,
                trigger: 4,
                initiatorDeviceJid: jid,
                initiatedByExternalService: true,
                initiatedByUserDevice: true,
                initiatedBySystem: true,
                initiatedByServer: true,
                initiatedByAdmin: true,
                initiatedByUser: true,
                initiatedByApp: true,
                initiatedByBot: true,
                initiatedByMe: true
            };

            await this.relayMessage(jid, img.message, {
                messageId: img.key.id,
                quoted: {
                    key: {
                        remoteJid: album.key.remoteJid,
                        id: album.key.id,
                        fromMe: true,
                        participant: userJid
                    },
                    message: album.message
                }
            });
        }

        return album;
    }

    async handleEvent(content, jid, quoted) {
        const eventData = content.eventMessage;

        const msg = await generateWAMessageFromContent(jid, {
            viewOnceMessage: {
                message: {
                    messageContextInfo: {
                        deviceListMetadata: {},
                        deviceListMetadataVersion: 2,
                        messageSecret: randomBytes(32),
                        supportPayload: JSON.stringify({
                            version: 2,
                            is_ai_message: true,
                            should_show_system_message: true,
                            ticket_id: randomBytes(16).toString('hex')
                        })
                    },
                    eventMessage: {
                        contextInfo: {
                            mentionedJid: [jid],
                            participant: jid,
                            remoteJid: 'status@broadcast',
                            forwardedNewsletterMessageInfo: {
                                newsletterName: 'shenvn.',
                                newsletterJid: '120363297591152843@newsletter',
                                serverMessageId: 1
                            }
                        },
                        isCanceled: eventData.isCanceled || false,
                        name: eventData.name,
                        description: eventData.description,
                        location: eventData.location || {
                            degreesLatitude: 0,
                            degreesLongitude: 0,
                            name: 'Location'
                        },
                        joinLink: eventData.joinLink || '',
                        startTime: typeof eventData.startTime === 'string'
                            ? parseInt(eventData.startTime)
                            : (eventData.startTime || Date.now()),
                        endTime: typeof eventData.endTime === 'string'
                            ? parseInt(eventData.endTime)
                            : (eventData.endTime || Date.now() + 3_600_000),
                        extraGuestsAllowed: eventData.extraGuestsAllowed !== false
                    }
                }
            }
        }, { quoted });

        await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
        return msg;
    }

    async handlePollResult(content, jid, quoted) {
        const pollData = content.pollResultMessage;

        const msg = await generateWAMessageFromContent(jid, {
            pollResultSnapshotMessage: {
                name: pollData.name,
                pollVotes: pollData.pollVotes.map(vote => ({
                    optionName: vote.optionName,
                    optionVoteCount: typeof vote.optionVoteCount === 'number'
                        ? vote.optionVoteCount.toString()
                        : vote.optionVoteCount
                }))
            }
        }, {
            userJid: this.meId,
            quoted
        });

        await this.relayMessage(jid, msg.message, { messageId: msg.key.id });
        return msg;
    }

    async handleGroupStory(content, jid, quoted) {
        const storyData = content.groupStatusMessage;
        let waMsgContent;

        if (storyData.message) {
            waMsgContent = storyData;
        } else {
            waMsgContent = await generateWAMessageContent(storyData, {
                upload: this.waUploadToServer
            });
        }

        const msg = {
            message: {
                groupStatusMessageV2: {
                    message: waMsgContent.message || waMsgContent
                }
            }
        };

        return await this.relayMessage(jid, msg.message, {
            messageId: generateMessageIDV2(this.meId)
        });
    }
}
//# sourceMappingURL=riyoo.js.map
