const express = require('express');
const puppeteer = require('puppeteer');
const handlebars = require('handlebars');
const path = require('path');
const fs = require('fs').promises;
const Document = require('../models/Document.cjs');
const Template = require('../models/Template.cjs');
const { auth } = require('../middleware/auth.cjs');

const router = express.Router();

// Register handlebars helpers
handlebars.registerHelper('formatDate', (date) => {
  if (!date) return '';
  return new Date(date).toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
});

handlebars.registerHelper('formatCurrency', (amount, currency = 'USD') => {
  if (amount === null || amount === undefined) return '';
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: currency
  }).format(amount);
});

handlebars.registerHelper('multiply', (a, b) => {
  return (a || 0) * (b || 0);
});

handlebars.registerHelper('eq', (a, b) => a === b);
handlebars.registerHelper('ne', (a, b) => a !== b);

// Generate PDF for document
// Generate PDF for document
// Generate PDF for document
router.get('/generate/:documentId', auth, async (req, res) => {
  let browser;
  let page;
  
  try {
    const document = await Document.findOne({
      _id: req.params.documentId,
      company: req.user.company._id
    })
      .populate('client')
      .populate('supplier')
      .populate('company')
      .populate('template');

    if (!document) {
      return res.status(404).json({ message: 'Document not found' });
    }

    let template = document.template;
    
    if (!template) {
      template = await Template.findOne({
        company: req.user.company._id,
        documentTypes: document.type,
        isDefault: true
      });
    }

    if (!template) {
      return res.status(400).json({ message: 'No template found' });
    }

    const templateData = {
      ...document.toJSON(),
      documentType: document.type.charAt(0).toUpperCase() + document.type.slice(1).replace('_', ' '),
      company: document.company.toJSON ? document.company.toJSON() : document.company
    };

    const compiledTemplate = handlebars.compile(template.htmlContent, {
      allowProtoPropertiesByDefault: true,
      allowProtoMethodsByDefault: true
    });
    const html = compiledTemplate(templateData);

    browser = await puppeteer.launch({
      headless: 'new',
      args: ['--no-sandbox', '--disable-setuid-sandbox']
    });
    
    page = await browser.newPage();
    await page.setContent(html, { waitUntil: 'networkidle0' });
    
    const pdfBuffer = await page.pdf({
      format: 'A4',
      printBackground: true,
      margin: { top: '20px', right: '20px', bottom: '20px', left: '20px' }
    });

    if (!pdfBuffer || pdfBuffer.length === 0) {
      throw new Error('Generated PDF is empty');
    }
    console.log(`PDF generated: ${pdfBuffer.length} bytes for ${document.number}`);

    // Save to filesystem
    const pdfDir = path.join(__dirname, '../pdfs');
    await fs.mkdir(pdfDir, { recursive: true });
    
    const filename = `${document.type}_${document.number.replace(/[^a-zA-Z0-9]/g, '_')}_${Date.now()}.pdf`;
    const filepath = path.join(pdfDir, filename);
    
    await fs.writeFile(filepath, pdfBuffer);

    // Update document
    document.pdfPath = filename;
    document.auditTrail.push({
      action: 'pdf_generated',
      user: req.user._id,
      details: 'PDF generated successfully'
    });
    await document.save();

    // FIXED: Explicit binary response (no wrappers)
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);  // Proper filename
    res.setHeader('Content-Length', pdfBuffer.length.toString());  // Explicit length
    res.removeHeader('Content-Encoding');  // Prevent gzip (can corrupt binary)
    
    res.end(pdfBuffer);  // FIXED: Use res.end for raw binary (vs res.send which may chunk)

  } catch (error) {
    console.error('PDF generation error:', error);
    if (!res.headersSent) {
      res.status(500).json({ message: 'Error generating PDF', detail: error.message });
    }
  } finally {
    if (page) await page.close().catch(console.warn);
    if (browser) await browser.close().catch(console.warn);
  }
});

// Download existing PDF
router.get('/download/:documentId', auth, async (req, res) => {
  try {
    const document = await Document.findOne({
      _id: req.params.documentId,
      company: req.user.company._id
    });

    if (!document || !document.pdfPath) {
      return res.status(404).json({ message: 'PDF not found' });
    }

    const filepath = path.join(__dirname, '../pdfs', document.pdfPath);
    
    try {
      await fs.access(filepath);
      res.download(filepath, document.pdfPath);
    } catch (error) {
      res.status(404).json({ message: 'PDF file not found on disk' });
    }
  } catch (error) {
    console.error('PDF download error:', error);
    res.status(500).json({ message: 'Error downloading PDF' });
  }
});

// Preview document as HTML
router.get('/preview/:documentId', auth, async (req, res) => {
  try {
    const document = await Document.findOne({
      _id: req.params.documentId,
      company: req.user.company._id
    })
      .populate('client')
      .populate('supplier')
      .populate('company')
      .populate('template');

    if (!document) {
      return res.status(404).json({ message: 'Document not found' });
    }

    let template = document.template;
    
    if (!template) {
      template = await Template.findOne({
        company: req.user.company._id,
        documentTypes: document.type,
        isDefault: true
      });
    }

    if (!template) {
      return res.status(400).json({ message: 'No template found' });
    }

    const templateData = {
      ...document.toObject(),
      documentType: document.type.charAt(0).toUpperCase() + document.type.slice(1).replace('_', ' '),
      company: document.company
    };

    const compiledTemplate = handlebars.compile(template.htmlContent);
    const html = compiledTemplate(templateData);

    res.set('Content-Type', 'text/html');
    res.send(html);
  } catch (error) {
    console.error('Preview error:', error);
    res.status(500).json({ message: 'Error generating preview' });
  }
});

module.exports = router;