import { NextRequest, NextResponse } from 'next/server' import { supabase } from '@/lib/supabase' import nodemailer from 'nodemailer' // API route configuration - dynamic for POST/GET requests export const dynamic = 'force-dynamic' export const runtime = 'nodejs' // Initialize nodemailer transporter const createTransporter = () => { const smtpHost = process.env.SMTP_HOST const smtpPort = process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT) : 587 const smtpUser = process.env.SMTP_USER const smtpPassword = process.env.SMTP_PASSWORD if (!smtpHost || !smtpUser || !smtpPassword) { throw new Error('SMTP credentials are missing') } return nodemailer.createTransport({ host: smtpHost, port: smtpPort, secure: smtpPort === 465, auth: { user: smtpUser, pass: smtpPassword, }, }) } // POST - Send message from retailer to user or vice versa export async function POST(request: NextRequest) { try { const { buildId, retailerEmail, userEmail, message, senderType, senderName } = await request.json() if (!buildId || !retailerEmail || !userEmail || !message || !senderType) { return NextResponse.json( { error: 'Missing required fields: buildId, retailerEmail, userEmail, message, senderType' }, { status: 400 } ) } // Fetch build data const { data: buildData, error: buildError } = await supabase .from('builds') .select(` build_id, build_name, users(email, user_name), build_components( components( retailers(retailer_name, email) ) ) `) .eq('build_id', buildId) .single() if (buildError || !buildData) { return NextResponse.json( { error: 'Build not found' }, { status: 404 } ) } const buildName = buildData.build_name const userName = (buildData.users as any)?.user_name || 'Customer' const userEmailFromDb = (buildData.users as any)?.email // Find retailer name const components = (buildData.build_components as any[]).map((bc: any) => bc.components) const retailer = components.find((c: any) => c.retailers?.email === retailerEmail)?.retailers const retailerName = retailer?.retailer_name || 'Retailer' // Store conversation in localStorage (in production, use database) const conversationKey = `buildmate-conversation-${buildId}-${retailerEmail}` // Create conversation entry const conversationEntry = { id: Date.now().toString(), buildId, retailerEmail, userEmail, message, senderType, // 'retailer' or 'user' senderName: senderName || (senderType === 'retailer' ? retailerName : userName), createdAt: new Date().toISOString(), } // Parse from email const fromEmailRaw = process.env.SMTP_FROM_EMAIL || 'noreply@buildmate.com' const fromName = process.env.SMTP_FROM_NAME || 'BUILDMATE' const fromEmail = fromEmailRaw.includes('<') ? fromEmailRaw.match(/<(.+)>/)?.[1] || fromEmailRaw : fromEmailRaw let transporter try { transporter = createTransporter() } catch (error: any) { return NextResponse.json( { error: 'Email service not configured' }, { status: 500 } ) } // Send email to the recipient const recipientEmail = senderType === 'retailer' ? userEmail : retailerEmail const recipientName = senderType === 'retailer' ? userName : retailerName const senderNameForEmail = senderName || (senderType === 'retailer' ? retailerName : userName) const emailHtml = `
New Message
You have received a new message regarding your purchase order:
Build Name: ${buildName}
Build ID: #${buildId}
${message}
Reply: You can reply to this message by responding directly to this email, or visit your purchase details page to continue the conversation.
This is an automated email from BUILDMATE. Please reply to continue the conversation.
© ${new Date().getFullYear()} BUILDMATE. All rights reserved.