import { NextRequest, NextResponse } from 'next/server'; import { admin } from '@/lib/firebase-admin'; import nodemailer from 'nodemailer'; function generatePrayerEmailHTML(message: string, subject: string) { // Parse the message to extract prayer details and stats const lines = message.split('\n'); const stats = { total: 0, active: 0, answered: 0, archived: 0 }; const activePrayers = []; const answeredPrayers = []; let inActiveSection = false; let inAnsweredSection = false; for (const line of lines) { if (line.includes('Total Prayers:')) { stats.total = parseInt(line.split(':')[1].trim()) || 0; } else if (line.includes('Active Prayers:')) { stats.active = parseInt(line.split(':')[1].trim()) || 0; } else if (line.includes('Answered Prayers:')) { stats.answered = parseInt(line.split(':')[1].trim()) || 0; } else if (line.includes('Archived Prayers:')) { stats.archived = parseInt(line.split(':')[1].trim()) || 0; } else if (line.includes('--- Your Active Prayers ---')) { inActiveSection = true; inAnsweredSection = false; } else if (line.includes('--- Recently Answered Prayers ---')) { inActiveSection = false; inAnsweredSection = true; } else if (inActiveSection && line.includes(' - ')) { const match = line.match(/(\d{4}-\d{2}-\d{2}) - (PRAYER|PRAISE): (.+)/); if (match) { activePrayers.push({ date: match[1], type: match[2].toLowerCase(), text: match[3] }); } } else if (inAnsweredSection && line.includes(' - ')) { const match = line.match(/(\d{4}-\d{2}-\d{2}) - (PRAYER|PRAISE): (.+)/); if (match) { answeredPrayers.push({ date: match[1], type: match[2].toLowerCase(), text: match[3] }); } } } const html = ` ${subject}

🙏 Prayer App

${subject}
${stats.total}
Total Prayers
${stats.active}
Active
${stats.answered}
Answered
${stats.archived}
Archived
${activePrayers.length > 0 ? `

📝 Your Active Prayers

${activePrayers.map(prayer => `
${prayer.type}
${new Date(prayer.date).toLocaleDateString()}
${prayer.text}
`).join('')}
` : `

🎉 All Caught Up!

You have no active prayers. Great job staying on top of your prayer life!

`} ${answeredPrayers.length > 0 ? `

🙏 Recently Answered Prayers

${answeredPrayers.map(prayer => `
${prayer.type}
${new Date(prayer.date).toLocaleDateString()}
${prayer.text}
`).join('')}
` : ''}
"Pray without ceasing"
— 1 Thessalonians 5:17
`; return html; } export async function GET() { try { console.log('🔄 Checking for scheduled emails...'); // Get SMTP config using Firebase Admin SDK const configDoc = await admin.firestore().collection('config').doc('smtp').get(); if (!configDoc.exists) { console.log('❌ SMTP configuration not found'); return NextResponse.json({ message: 'SMTP configuration not found' }, { status: 500 }); } const smtpConfig = configDoc.data(); // Create transporter const transporter = nodemailer.createTransport({ host: smtpConfig.host, port: smtpConfig.port, secure: smtpConfig.secure, auth: { user: smtpConfig.user, pass: smtpConfig.pass, }, }); // Get all users (send daily emails to everyone) using Firebase Admin SDK const usersSnapshot = await admin.firestore().collection('users').get(); let emailsSent = 0; for (const userDoc of usersSnapshot.docs) { const userData = userDoc.data(); const userId = userDoc.id; // Skip users without email if (!userData.email) { continue; } // Check last email sent time - send daily const lastEmailSent = userData.lastEmailSent ? new Date(userData.lastEmailSent.toDate()) : new Date(0); const now = new Date(); // Send if more than 24 hours have passed const shouldSendEmail = (now.getTime() - lastEmailSent.getTime()) > (24 * 60 * 60 * 1000); if (!shouldSendEmail) { continue; } // Get user's prayers for stats using Firebase Admin SDK const prayersSnapshot = await admin.firestore().collection('prayers').where('userId', '==', userId).get(); const userPrayers = prayersSnapshot.docs.map(doc => doc.data()); // Calculate stats const activePrayers = userPrayers.filter(p => !p.archived); const archivedPrayers = userPrayers.filter(p => p.archived); const answeredPrayers = userPrayers.filter(p => p.answered); const totalPrayers = userPrayers.length; // Build email content with stats let message = `--- Daily Prayer Summary ---\n\n`; message += `📊 Your Prayer Statistics:\n`; message += `• Total Prayers: ${totalPrayers}\n`; message += `• Active Prayers: ${activePrayers.length}\n`; message += `• Answered Prayers: ${answeredPrayers.length}\n`; message += `• Archived Prayers: ${archivedPrayers.length}\n\n`; if (activePrayers.length > 0) { message += `--- Your Active Prayers ---\n`; activePrayers.forEach(prayer => { message += `\n${prayer.date} - ${prayer.type.toUpperCase()}: ${prayer.text}`; if (prayer.prayFor) { message += ` (Praying for: ${prayer.prayFor})`; } if (prayer.journal) { message += `\n Journal: ${prayer.journal}`; } message += `\n`; }); } else { message += `🎉 Great job! You have no active prayers - all caught up!\n\n`; } if (answeredPrayers.length > 0) { message += `\n--- Recently Answered Prayers ---\n`; // Show answered prayers from the last 7 days const recentAnswered = answeredPrayers.filter(p => { const answeredDate = p.answeredDate ? new Date(p.answeredDate) : new Date(p.date); const weekAgo = new Date(); weekAgo.setDate(weekAgo.getDate() - 7); return answeredDate >= weekAgo; }); if (recentAnswered.length > 0) { recentAnswered.forEach(prayer => { message += `\n${prayer.date} - ${prayer.type.toUpperCase()}: ${prayer.text}`; if (prayer.answeredDate) { message += ` (Answered: ${new Date(prayer.answeredDate).toLocaleDateString()})`; } message += `\n`; }); } } const subject = `Daily Prayer Summary - ${activePrayers.length} active prayers`; try { // Send email await transporter.sendMail({ from: smtpConfig.from, to: userData.email, subject, text: message, html: generatePrayerEmailHTML(message, subject), }); // Update last email sent time using Firebase Admin SDK await admin.firestore().collection('users').doc(userId).update({ lastEmailSent: new Date(), }); emailsSent++; console.log(`✅ Sent daily summary email to ${userData.email}`); } catch (emailError) { console.error(`❌ Failed to send email to ${userData.email}:`, emailError); } } console.log(`📧 Daily email summary complete. Sent ${emailsSent} emails.`); return NextResponse.json({ message: `Daily email summary complete. Sent ${emailsSent} emails.`, emailsSent }); } catch (error) { console.error('❌ Scheduled email error:', error); console.error('❌ Error details:', { message: error instanceof Error ? error.message : 'Unknown error', stack: error instanceof Error ? error.stack : undefined, name: error instanceof Error ? error.name : 'Unknown' }); return NextResponse.json({ error: 'Failed to process scheduled emails', details: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 }); } } export async function POST() { // POST handler calls the same logic as GET for testing purposes return GET(); }