import { prisma } from "@/lib/prisma"; // Define strict types for the webhook payload interface WebhookEvent { entry: Array<{ id: string; // Instagram Business Account ID time: number; changes: Array<{ field: string; value: { from: { id: string; // User ID who commented username: string; // Username of commenter }; media: { id: string; // Media ID (Post ID) product_type?: string; }; id: string; // Comment ID text: string; // Comment text created_time: number; parent_id?: string; // If it's a reply to a comment }; }>; }>; } export async function processCommentEvent(body: WebhookEvent) { if (!body.entry || body.entry.length === 0) return; for (const entry of body.entry) { for (const change of entry.changes) { if (change.field === "comments") { const value = change.value; const mediaId = value.media.id; const commentText = value.text; const commentId = value.id; const userId = value.from.id; // 1. Find the local Post relating to this Instagram Media ID // Note: We need to store instagramMediaId in our Post model to map this back. // Assuming we have it. If not, we might fail to match. console.log(`[Automation] Processing comment ${commentId} on media ${mediaId} from user ${userId}`); // 1. Find the local Post relating to this Instagram Media ID const post = await prisma.post.findFirst({ where: { instagramMediaId: mediaId }, include: { automations: { where: { isActive: true }, include: { keywords: true, replies: true } }, instagramAccount: true } }); if (!post) { console.log(`[Automation] No local post found for IG Media ID: ${mediaId}`); continue; } if (post.automations.length === 0) { console.log(`[Automation] Post found (ID: ${post.id}), but no active automations.`); continue; } const automation = post.automations[0]; const keywords = automation.keywords.map(k => k.keyword.toLowerCase().trim()); // 2. Check for Keyword Match const lowerText = commentText.toLowerCase(); console.log(`[Automation] Checking text: "${lowerText}" against keywords: [${keywords.join(", ")}]`); const matched = keywords.some(k => lowerText.includes(k)); if (matched) { console.log(`[Automation] Keyword matched! Executing actions...`); const accessToken = post.instagramAccount?.accessToken; if (!accessToken) { console.error("[Automation] No access token found for account."); continue; } // 3. Send Public Reply if (automation.replies.length > 0) { const randomReply = automation.replies[Math.floor(Math.random() * automation.replies.length)]; await sendInstagramReply(commentId, randomReply.replyText, accessToken); } // 4. Send DM if (automation.dmMessage) { await sendInstagramDM(userId, automation.dmMessage, automation.dmLinkText, automation.dmLinkUrl, accessToken); } } } } } } async function sendInstagramReply(commentId: string, text: string, accessToken: string) { try { const url = `https://graph.facebook.com/v21.0/${commentId}/replies`; const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text, access_token: accessToken }) }); const data = await res.json(); if (!data.id) { console.error("Failed to send reply:", data); } else { console.log("Reply sent:", data.id); } } catch (e) { console.error("Error sending reply:", e); } } async function sendInstagramDM(userId: string, text: string, linkText: string | null | undefined, linkUrl: string | null | undefined, accessToken: string) { try { // NOTE: Sending DMs via API typically requires 'messages' scope and often uses 'IG Send API'. // However, generic "messages" endpoint on Graph API usually works for Business accounts communicating with users who interacted. // Structure for a generic message const body: any = { recipient: { id: userId }, message: { text: text }, access_token: accessToken }; // If a button is required, it might need "Generic Template" structure, // but for simplicity/reliability safely, we append the link to text if button not supported easily in basic tier. // Let's try to append link if present as text for higher success rate unless we are sure about "Generic Template". // The user request showed a "Button". // IG Send API with Generic Template for button: if (linkText && linkUrl) { body.message = { attachment: { type: "template", payload: { template_type: "button", text: text, buttons: [ { type: "web_url", url: linkUrl, title: linkText } ] } } }; } const url = `https://graph.facebook.com/v21.0/me/messages`; // 'me' refers to the Page/account linked to token // Actually for Instagram Graph API, it's typically POST /{ig-user-id}/messages // Use the token to inspect 'me' or just assume flow relative to token owner. // Better: POST https://graph.facebook.com/v21.0/me/messages with access_token of the IG Business User. const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); const data = await res.json(); if (!data.message_id) { console.error("Failed to send DM:", data); // Fallback: try sending just text if template failed? } else { console.log("DM sent:", data.message_id); } } catch (e) { console.error("Error sending DM:", e); } }