import { Hono } from "npm:hono"; import { cors } from "npm:hono/cors"; import { logger } from "npm:hono/logger"; import * as kv from "./kv_store.tsx"; const app = new Hono(); // Enable logger app.use('*', logger(console.log)); // Enable CORS for all routes and methods app.use( "/*", cors({ origin: "*", allowHeaders: ["Content-Type", "Authorization"], allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], exposeHeaders: ["Content-Length"], maxAge: 600, }), ); // Health check endpoint app.get("/make-server-10d555e8/health", (c) => { return c.json({ status: "ok" }); }); // Test email configuration endpoint app.get("/make-server-10d555e8/test-email-config", (c) => { const resendApiKey = Deno.env.get('RESEND_API_KEY'); return c.json({ emailConfigured: !!resendApiKey, apiKeyFormat: resendApiKey ? (resendApiKey.startsWith('re_') ? 'valid' : 'invalid') : 'missing', apiKeyLength: resendApiKey?.length || 0 }); }); // Email endpoint for booking confirmations app.post("/make-server-10d555e8/send-booking-email", async (c) => { try { const bookingData = await c.req.json(); console.log('Received booking data:', JSON.stringify(bookingData, null, 2)); // Store booking in KV store const bookingId = `booking_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; await kv.set(bookingId, { ...bookingData, bookingId, createdAt: new Date().toISOString(), status: 'confirmed' }); console.log('Booking stored with ID:', bookingId); const resendApiKey = Deno.env.get('RESEND_API_KEY'); console.log('API Key exists:', !!resendApiKey); console.log('API Key length:', resendApiKey?.length || 0); console.log('API Key prefix:', resendApiKey?.substring(0, 7) || 'none'); if (!resendApiKey) { console.error('RESEND_API_KEY environment variable not found'); throw new Error('RESEND_API_KEY not configured - please set up your Resend API key'); } // Validate API key format (Resend keys typically start with 're_') if (!resendApiKey.startsWith('re_')) { console.error('Invalid API key format. Resend API keys should start with "re_"'); throw new Error('Invalid RESEND_API_KEY format - Resend API keys should start with "re_"'); } // Get vehicle pricing const getVehiclePrice = (vehicleType) => { switch (vehicleType) { case '5-seater': return '₹999'; case '7-seater': return '₹1600'; case 'innova': return '₹2000'; default: return 'Contact for pricing'; } }; const price = getVehiclePrice(bookingData.vehicleType); // Email content for business owner const businessEmailContent = `

🚗 New Taxi Booking - Sangwari Taxi

Booking Details

Booking ID: ${bookingId}

Customer Name: ${bookingData.contactName}

Contact Number: ${bookingData.contactNumber}

Pickup Location: ${bookingData.pickup}

Drop-off Location: ${bookingData.dropoff}

Date: ${bookingData.date}

Time: ${bookingData.time}

Passengers: ${bookingData.passengers}

Vehicle Type: ${bookingData.vehicleType} (${price})

Booking Time: ${new Date().toLocaleString('en-IN')}

Action Required: Please contact the customer to confirm pickup details and arrange the taxi service.

`; // Email content for customer const customerEmailContent = `

🚗 Booking Confirmed - Sangwari Taxi

Dear ${bookingData.contactName},

Thank you for choosing Sangwari Taxi! Your booking has been confirmed.

Booking Details:

Booking ID: ${bookingId}

Pickup Location: ${bookingData.pickup}

Drop-off Location: ${bookingData.dropoff}

Date: ${bookingData.date}

Time: ${bookingData.time}

Passengers: ${bookingData.passengers}

Vehicle Type: ${bookingData.vehicleType} (${price})

Next Steps: Our team will contact you shortly to confirm pickup details. Please keep your phone available.

Contact Information:

Phone: 7477247488

Email: bookme@sangwaritaxi.com

Address: Commercial complex second floor Nehru Nagar east Bhilai beside state bank Pin 490020

Thank you for choosing Sangwari Taxi. We look forward to serving you!

`; // Send email to business owner console.log('Attempting to send business email...'); const businessEmailResponse = await fetch('https://api.resend.com/emails', { method: 'POST', headers: { 'Authorization': `Bearer ${resendApiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ from: 'Sangwari Taxi ', to: ['bookme@sangwaritaxi.com'], subject: `New Taxi Booking #${bookingId} - ${bookingData.contactName}`, html: businessEmailContent, }), }); const businessEmailResult = await businessEmailResponse.text(); console.log('Business email response status:', businessEmailResponse.status); console.log('Business email response:', businessEmailResult); if (!businessEmailResponse.ok) { console.error('Failed to send business email:', businessEmailResult); throw new Error(`Failed to send business email: ${businessEmailResult}`); } // Send confirmation email to customer (if they provided email) let customerEmailResponse = null; if (bookingData.customerEmail && bookingData.customerEmail.trim() !== '') { console.log('Attempting to send customer email to:', bookingData.customerEmail); customerEmailResponse = await fetch('https://api.resend.com/emails', { method: 'POST', headers: { 'Authorization': `Bearer ${resendApiKey}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ from: 'Sangwari Taxi ', to: [bookingData.customerEmail], subject: `Booking Confirmed #${bookingId} - Sangwari Taxi`, html: customerEmailContent, }), }); const customerEmailResult = await customerEmailResponse.text(); console.log('Customer email response status:', customerEmailResponse.status); console.log('Customer email response:', customerEmailResult); if (!customerEmailResponse.ok) { console.error('Failed to send customer email:', customerEmailResult); // Don't fail the whole request if customer email fails } } else { console.log('No customer email provided, skipping customer notification'); } console.log('Booking email sent successfully:', bookingId); return c.json({ success: true, message: 'Booking confirmed and emails sent successfully', bookingId: bookingId, emailsSent: { business: true, customer: !!customerEmailResponse?.ok } }); } catch (error) { console.error('Error processing booking:', error); // If it's an API key issue, provide specific guidance if (error.message.includes('API key') || error.message.includes('validation_error')) { return c.json({ success: false, message: `Email service configuration error: ${error.message}. Please check your Resend API key setup.`, error: 'EMAIL_CONFIG_ERROR' }, 400); } // For other errors, still save the booking but indicate email failure return c.json({ success: false, message: `Booking saved but email notification failed: ${error.message}`, error: 'EMAIL_SEND_FAILED' }, 500); } }); Deno.serve(app.fetch);