import NextAuth, { NextAuthOptions } from "next-auth"; import FacebookProvider from "next-auth/providers/facebook"; import { PrismaClient } from "@prisma/client"; // Initialize Prisma Client (singleton pattern recommended for dev, keeping simplistic for now or importing from lib/prisma if I create it) // For now, I'll assume global prisma or import it. I should create src/lib/prisma.ts first. import { prisma } from "@/lib/prisma"; import { encrypt } from "@/lib/encryption"; export const authOptions: NextAuthOptions = { providers: [ FacebookProvider({ clientId: process.env.FACEBOOK_APP_ID!, clientSecret: process.env.FACEBOOK_APP_SECRET!, authorization: { params: { scope: "public_profile,instagram_basic,instagram_content_publish,pages_show_list,pages_read_engagement,business_management", }, }, }), ], callbacks: { async signIn({ user, account, profile }) { if (account?.provider === "facebook" && account.access_token) { try { console.log("Starting Facebook Sign In Process..."); // 1. Exchange for Long-Lived Token (LLT) const graphUrl = process.env.INSTAGRAM_GRAPH_URL || "https://graph.facebook.com/v21.0"; const exchangeUrl = `${graphUrl}/oauth/access_token?grant_type=fb_exchange_token&client_id=${process.env.FACEBOOK_APP_ID}&client_secret=${process.env.FACEBOOK_APP_SECRET}&fb_exchange_token=${account.access_token}`; console.log("Exchanging token..."); const exchangeRes = await fetch(exchangeUrl); const exchangeData = await exchangeRes.json(); if (!exchangeRes.ok || !exchangeData.access_token) { console.error("Failed to exchange token", exchangeData); return false; } console.log("Token exchanged successfully."); const longLivedToken = exchangeData.access_token; // Calculate expiry (usually 60 days) const expiresAt = new Date(); expiresAt.setDate(expiresAt.getDate() + 60); // 2. Fetch accessible Pages and their connected Instagram Accounts console.log("Fetching pages..."); const pagesUrl = `${graphUrl}/me/accounts?fields=id,name,access_token,instagram_business_account{id,username,profile_picture_url}&access_token=${longLivedToken}`; const pagesRes = await fetch(pagesUrl); const pagesData = await pagesRes.json(); if (!pagesRes.ok) { console.error("Failed to fetch accounts", pagesData); return false; } console.log("Pages fetched from FB:", pagesData.data?.length); // Log details of each page if (pagesData.data) { pagesData.data.forEach((p: any) => { console.log(`Page: ${p.name} (ID: ${p.id})`); console.log(` - Has IG Object: ${!!p.instagram_business_account}`); }); } const connectedAccounts = (pagesData.data || []).filter((page: any) => page.instagram_business_account); if (connectedAccounts.length === 0) { console.warn("No Instagram Business accounts found. Raw pages data:", JSON.stringify(pagesData.data, null, 2)); // Allow login properly even if no accounts found, so user can see dashboard and realize they need to connect one. // Previously we might have been implicitely failing if logic depended on it? No, logic flow continues. } // 3. Create or Update User const email = user.email || `${user.id}@ripple.user`; const userImage = user.image || null; user.email = email; console.log("Upserting User:", email); const dbUser = await prisma.user.upsert({ where: { email }, update: { image: userImage }, create: { email, id: user.id || crypto.randomUUID(), image: userImage }, // Ensure ID is present }); console.log("User upserted:", dbUser.id); // 4. Save Instagram Accounts if (connectedAccounts.length > 0) { console.log(`Saving ${connectedAccounts.length} Instagram Accounts...`); for (const page of connectedAccounts) { const ig = page.instagram_business_account; const encryptedToken = encrypt(longLivedToken); await prisma.instagramAccount.upsert({ where: { instagramUserId: ig.id }, update: { username: ig.username, profilePictureUrl: ig.profile_picture_url, accessToken: encryptedToken, tokenExpiresAt: expiresAt, userId: dbUser.id, }, create: { instagramUserId: ig.id, username: ig.username, profilePictureUrl: ig.profile_picture_url, accessToken: encryptedToken, tokenExpiresAt: expiresAt, userId: dbUser.id, }, }); } console.log("Instagram Accounts saved."); } else { console.log("Skipping IG Account save (None found)."); } console.log("Sign In Logic Completed Successfully."); return true; } catch (error) { console.error("SignIn CRITICAL ERROR:", error); return false; } } return true; }, async jwt({ token, user, account }) { // Initial sign in if (account && user) { token.accessToken = account.access_token; token.id = user.id; // Ensure email is set in token if (user.email) { token.email = user.email; } else if (user.id) { token.email = `${user.id}@ripple.user`; } // Allow passing image if needed, but session typically reads from DB or user object if (user.image) token.picture = user.image; } return token; }, async session({ session, token }) { session.accessToken = token.accessToken as string; if (session.user) { (session.user as any).id = token.id as string; if (token.email) { session.user.email = token.email; } if (token.picture) { session.user.image = token.picture; } } return session; }, }, pages: { signIn: '/auth/signin', }, // @ts-ignore trustHost: true, };