import { onRequest } from "firebase-functions/v2/https"; import { Request } from "firebase-functions/v2/https"; import { getCorsHandler } from "../../../shared/middleware"; import { getAdmin, getLogger } from "../../../shared/config"; import { InvoiceService, InvoiceData } from "./invoiceService"; const admin = getAdmin(); const logger = getLogger(); const corsHandler = getCorsHandler(); const invoiceService = new InvoiceService(); export const directGenerateInvoice = onRequest({ region: '#{SERVICES_RGN}#' }, async (request: Request, response) => { return corsHandler(request, response, async () => { try { const authHeader = request.headers.authorization || ''; if (!authHeader || !authHeader.startsWith('Bearer ')) { response.status(401).json({ error: 'Unauthorized' }); return; } const idToken = authHeader.split('Bearer ')[1]; try { await admin.auth().verifyIdToken(idToken); const { invoiceNumber, businessName, address, gstNumber, customerName, phoneNumber, email, planName, amount, transactionId, paymentDate, paymentMethod, sendEmail, emailOptions } = request.body; if (!invoiceNumber || !businessName || !customerName || !amount || !transactionId) { response.status(400).json({ success: false, error: 'Missing required fields' }); return; } const invoiceData: InvoiceData = { invoiceNumber, businessName, address: address || '', gstNumber, customerName, phoneNumber: phoneNumber || '', email: email || '', planName: planName || 'Membership', amount: parseFloat(amount), transactionId, paymentDate: paymentDate ? new Date(paymentDate) : new Date(), paymentMethod: paymentMethod || 'Online' }; const invoicePath = await invoiceService.generateInvoice(invoiceData); const downloadUrl = await invoiceService.getInvoiceDownloadUrl(invoicePath); let emailSent = false; if (sendEmail && email) { emailSent = await invoiceService.sendInvoiceEmail(invoicePath, { recipientEmail: email, recipientName: customerName, ...emailOptions }); } response.json({ success: true, invoicePath, downloadUrl, emailSent }); } catch (authError: any) { logger.error('Authentication error:', authError); response.status(401).json({ success: false, error: 'Invalid authentication token', details: authError.message }); } } catch (error: any) { logger.error('Error generating invoice:', error); response.status(500).json({ success: false, error: 'Failed to generate invoice', details: error.message }); } }); });