import { NextRequest, NextResponse } from 'next/server' import nodemailer from 'nodemailer' // API route configuration - dynamic for POST requests export const dynamic = 'force-dynamic' export const runtime = 'nodejs' // Ticket emails are sent via Gmail when SMTP_HOST=smtp.gmail.com (use Gmail App Password in SMTP_PASSWORD). const createTransporter = () => { const smtpHost = process.env.SMTP_HOST const smtpPort = process.env.SMTP_PORT ? parseInt(process.env.SMTP_PORT, 10) : 587 const smtpUser = process.env.SMTP_USER?.trim() // Gmail App Passwords may be pasted with spaces; remove for auth const smtpPassword = (process.env.SMTP_PASSWORD || '').replace(/\s/g, '').trim() const smtpFromEmail = process.env.SMTP_FROM_EMAIL || 'BUILDMATE ' const smtpFromName = process.env.SMTP_FROM_NAME || 'BUILDMATE' const isPlaceholder = (smtpHost?.trim() === 'your_smtp_host') || (smtpUser === 'your_smtp_user') || (smtpPassword === 'your_smtp_password') if (isPlaceholder) { throw new Error('SMTP credentials in .env.local are still placeholders. Please replace them with actual values.') } if (!smtpHost || !smtpUser || !smtpPassword) { throw new Error('SMTP credentials (host, user, password) are missing in environment variables.') } const isGmail = smtpHost.toLowerCase().includes('gmail.com') const port = smtpPort || 587 const secure = port === 465 return nodemailer.createTransport({ host: smtpHost, port, secure, ...(isGmail && { requireTLS: true }), auth: { user: smtpUser, pass: smtpPassword, }, }) } export async function POST(request: NextRequest) { try { const ticketData = await request.json() if (!ticketData) { return NextResponse.json( { error: 'Ticket data is required' }, { status: 400 } ) } const { id, title, type, priority, status, description, createdAt, userName, userEmail, buildId, assignedTo } = ticketData // Validate required fields if (!id || !title || !type || !description) { return NextResponse.json( { error: 'Missing required ticket fields' }, { status: 400 } ) } // Get support type label const supportTypeLabels: Record = { troubleshooting: 'Troubleshooting', build_problem: 'Build Problem', delivery: 'Delivery/Repair', general: 'General Inquiry' } // Get priority label const priorityLabels: Record = { low: 'Low', medium: 'Medium', high: 'High', urgent: 'Urgent' } const supportTypeLabel = supportTypeLabels[type] || type const priorityLabel = priorityLabels[priority] || priority // Create HTML email content const emailHtml = ` New Support Ticket - ${id}

BUILDMATE

New Support Ticket

New Support Ticket Created

A customer has submitted a new support ticket. Please review and respond accordingly.

Ticket Information

Ticket ID: ${id}

Title: ${title}

Type: ${supportTypeLabel}

Priority: ${priorityLabel}

Status: ${status}

Date Created: ${new Date(createdAt || new Date().toISOString()).toLocaleString()}

${assignedTo ? `

Assigned To: ${assignedTo}

` : ''}

Customer Information

${userName ? `

Customer Name: ${userName}

` : ''} ${userEmail ? `

Customer Email: ${userEmail}

` : ''} ${buildId ? `

Related Build ID: ${buildId}

` : ''}

Description

${description}

Action Required: Please review this ticket and respond to the customer as soon as possible. ${userEmail ? `You can reply directly to this email to contact the customer at ${userEmail}.` : ''}

This is an automated email from BUILDMATE Support System.

© ${new Date().getFullYear()} BUILDMATE. All rights reserved.

` // Send email using Nodemailer let transporter try { transporter = createTransporter() } catch (transporterError: any) { console.error('❌ SMTP configuration error:', transporterError.message) if (process.env.NODE_ENV === 'development') { return NextResponse.json({ success: false, error: transporterError.message, message: 'Please configure SMTP in .env.local' }) } return NextResponse.json( { error: 'Email service not configured. Please configure SMTP settings.' }, { status: 500 } ) } if (!transporter) { return NextResponse.json( { error: 'Email service not configured. Please configure SMTP settings.' }, { status: 500 } ) } // 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 // Always send to Central Juan Solution email const CENTRAL_JUAN_EMAIL = 'sales.centraljuan.net@gmail.com' // Also send copy to admin email for verification const ADMIN_EMAIL = 'dummy.dumm.acc001@gmail.com' try { await transporter.verify() console.log('✅ SMTP connection verified') const mailOptions = { from: `${fromName} <${fromEmail}>`, to: CENTRAL_JUAN_EMAIL, cc: ADMIN_EMAIL, // Send copy to admin email so they can verify it was sent replyTo: userEmail || fromEmail, subject: `New Support Ticket - ${id}: ${title}`, html: emailHtml, } const emailInfo = await transporter.sendMail(mailOptions) console.log('✅ Support ticket email sent to Central Juan Solution:', emailInfo.messageId) console.log(`📧 Email sent to: ${CENTRAL_JUAN_EMAIL} (CC: ${ADMIN_EMAIL})`) return NextResponse.json({ success: true, message: 'Support ticket notification sent successfully', emailSent: true, messageId: emailInfo.messageId, sentTo: CENTRAL_JUAN_EMAIL, ccTo: ADMIN_EMAIL }) } catch (emailError: any) { console.error('❌ Error sending support ticket email:', emailError) return NextResponse.json( { success: false, error: 'Failed to send support ticket email', details: emailError.message }, { status: 500 } ) } } catch (error: any) { console.error('Send support ticket email error:', error) return NextResponse.json( { error: error.message || 'Internal server error' }, { status: 500 } ) } }