← back to Dear Bubbe Nextjs
app/api/send-welcome-email/route.ts
157 lines
import { NextRequest, NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'
import { generateWelcomeEmail } from '@/lib/email-templates/welcome'
// Create emails directory if it doesn't exist
const emailsDir = path.join(process.cwd(), 'data', 'emails')
if (!fs.existsSync(emailsDir)) {
fs.mkdirSync(emailsDir, { recursive: true })
}
interface EmailRequest {
to: string
name?: string
userId?: string
profile?: any
}
// Since we don't have a real email service, we'll log and save emails
async function mockSendEmail(emailData: {
to: string
subject: string
html: string
text: string
}) {
// Create a unique filename with timestamp
const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
const filename = `welcome-${timestamp}-${emailData.to.replace('@', '_at_')}.json`
const filePath = path.join(emailsDir, filename)
// Log the email send
console.log('[EMAIL] 📧 Sending welcome email to:', emailData.to)
console.log('[EMAIL] Subject:', emailData.subject)
// Save email record to disk
const emailRecord = {
id: `email-${Date.now()}`,
type: 'welcome',
to: emailData.to,
subject: emailData.subject,
html: emailData.html,
text: emailData.text,
sentAt: new Date().toISOString(),
status: 'sent' // In production, this would come from email service
}
fs.writeFileSync(filePath, JSON.stringify(emailRecord, null, 2))
console.log('[EMAIL] ✅ Email saved to:', filePath)
// In production, this would use a service like SendGrid, AWS SES, etc.
// await sendgrid.send(emailData)
return emailRecord
}
export async function POST(request: NextRequest) {
try {
const body: EmailRequest = await request.json()
if (!body.to) {
return NextResponse.json(
{ error: 'Email address is required' },
{ status: 400 }
)
}
// Generate the email content
const { html, text } = generateWelcomeEmail({
name: body.name || 'Bubbeleh',
email: body.to,
userId: body.userId,
profile: body.profile
})
// Prepare email data
const emailData = {
to: body.to,
subject: "Welcome to Dear Bubbe - Your Jewish Grandma is Here! 👵",
html: html,
text: text
}
// Send the email (mocked for now)
const result = await mockSendEmail(emailData)
// Log success
console.log('[EMAIL] 🎉 Welcome email successfully sent to:', body.to)
return NextResponse.json({
success: true,
message: 'Welcome email sent successfully',
emailId: result.id,
to: body.to
})
} catch (error) {
console.error('[EMAIL] ❌ Error sending welcome email:', error)
return NextResponse.json(
{
success: false,
error: 'Failed to send welcome email',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
)
}
}
// GET endpoint to retrieve email history
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url)
const email = searchParams.get('email')
// Read all email files
const files = fs.readdirSync(emailsDir)
let emails = []
for (const file of files) {
if (file.endsWith('.json')) {
const content = fs.readFileSync(path.join(emailsDir, file), 'utf-8')
const emailRecord = JSON.parse(content)
// Filter by email if specified
if (!email || emailRecord.to === email) {
emails.push({
...emailRecord,
// Don't include full HTML in listing
html: undefined,
htmlLength: emailRecord.html?.length || 0
})
}
}
}
// Sort by date, newest first
emails.sort((a, b) =>
new Date(b.sentAt).getTime() - new Date(a.sentAt).getTime()
)
return NextResponse.json({
success: true,
count: emails.length,
emails: emails
})
} catch (error) {
console.error('[EMAIL] Error retrieving email history:', error)
return NextResponse.json(
{
success: false,
error: 'Failed to retrieve email history'
},
{ status: 500 }
)
}
}