const PDFDocument = require('pdfkit');
const path = require('path');
const fs = require('fs');

class InvoiceService {
  async generateInvoice(order, orderItems) {
    const doc = new PDFDocument({ size: 'A4', margin: 50 });
    const buffers = [];

    return new Promise((resolve, reject) => {
      doc.on('data', (chunk) => buffers.push(chunk));
      doc.on('end', () => resolve(Buffer.concat(buffers)));
      doc.on('error', reject);

      const appName = process.env.APP_NAME || 'ShopNow';

      // Header
      doc.fontSize(24).text(appName, { align: 'center' });
      doc.fontSize(10).text('123 Main Street, City, State - 000001', { align: 'center' });
      doc.text('Phone: +91 9876543210 | Email: support@shopnow.com', { align: 'center' });
      doc.moveDown();

      // Invoice Title
      doc.moveTo(50, doc.y).lineTo(545, doc.y).stroke();
      doc.moveDown(0.5);
      doc.fontSize(18).text('INVOICE', { align: 'center' });
      doc.moveDown(0.5);
      doc.moveTo(50, doc.y).lineTo(545, doc.y).stroke();
      doc.moveDown();

      // Order info
      doc.fontSize(10);
      doc.text(`Invoice #: ${order.orderNumber}`);
      doc.text(`Date: ${new Date(order.createdAt).toLocaleDateString('en-IN')}`);
      doc.text(`Order Status: ${order.status.toUpperCase()}`);
      doc.text(`Payment: ${order.paymentMethod.toUpperCase()} (${order.paymentStatus})`);
      doc.moveDown();

      // Shipping Address
      doc.fontSize(12).text('Ship To:', { underline: true });
      doc.fontSize(10);
      doc.text(order.shippingName);
      doc.text(order.shippingAddress);
      doc.text(`${order.shippingCity}, ${order.shippingState} - ${order.shippingPincode}`);
      doc.text(`Phone: ${order.shippingPhone}`);
      doc.moveDown(1.5);

      // Items table header
      const tableTop = doc.y;
      doc.fontSize(10).font('Helvetica-Bold');
      doc.text('Item', 50, tableTop, { width: 250 });
      doc.text('Qty', 310, tableTop, { width: 50, align: 'center' });
      doc.text('Price', 370, tableTop, { width: 80, align: 'right' });
      doc.text('Total', 460, tableTop, { width: 80, align: 'right' });
      doc.moveTo(50, doc.y + 5).lineTo(545, doc.y + 5).stroke();
      doc.moveDown(0.5);

      doc.font('Helvetica');
      let y = doc.y;
      for (const item of orderItems) {
        doc.text(item.productName, 50, y, { width: 250 });
        doc.text(String(item.quantity), 310, y, { width: 50, align: 'center' });
        doc.text(`₹${parseFloat(item.unitPrice).toFixed(2)}`, 370, y, { width: 80, align: 'right' });
        doc.text(`₹${parseFloat(item.total).toFixed(2)}`, 460, y, { width: 80, align: 'right' });
        y += 20;
      }

      doc.moveTo(50, y + 5).lineTo(545, y + 5).stroke();
      y += 15;
      doc.font('Helvetica-Bold');

      // Totals
      const xRight = 370;
      doc.text('Subtotal:', xRight, y);
      doc.text(`₹${parseFloat(order.subtotal).toFixed(2)}`, 460, y, { width: 80, align: 'right' });
      y += 18;
      doc.text('Shipping:', xRight, y);
      doc.text(`₹${parseFloat(order.shippingAmount).toFixed(2)}`, 460, y, { width: 80, align: 'right' });
      y += 18;
      doc.text('Tax:', xRight, y);
      doc.text(`₹${parseFloat(order.taxAmount).toFixed(2)}`, 460, y, { width: 80, align: 'right' });
      y += 18;
      if (parseFloat(order.discountAmount) > 0) {
        doc.text('Discount:', xRight, y);
        doc.text(`-₹${parseFloat(order.discountAmount).toFixed(2)}`, 460, y, { width: 80, align: 'right' });
        y += 18;
      }
      doc.fontSize(14).text('Total:', xRight, y);
      doc.text(`₹${parseFloat(order.total).toFixed(2)}`, 460, y, { width: 80, align: 'right' });

      // Footer
      doc.fontSize(8).font('Helvetica');
      doc.moveDown(3);
      doc.moveTo(50, doc.y).lineTo(545, doc.y).stroke();
      doc.moveDown(0.5);
      doc.text('Thank you for your purchase!', { align: 'center' });
      doc.text(`Generated on ${new Date().toLocaleString('en-IN')}`, { align: 'center' });

      doc.end();
    });
  }
}

module.exports = new InvoiceService();
