const express = require('express');
const EmailSender = require('../services/email');
const InvoicesDBApi = require('../db/api/invoices');
const wrapAsync = require('../helpers').wrapAsync;
const { checkPermissions } = require('../middlewares/check-permissions');

const router = express.Router();

const escapeHtml = (value) => String(value || '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;')
  .replace(/'/g, '&#039;');

router.post('/invoice-email', checkPermissions('READ_INVOICES'), wrapAsync(async (req, res) => {
  const { invoiceId, recipientEmail, note, workflowStage, sourceUrl } = req.body || {};

  if (!invoiceId) {
    return res.status(400).send({ message: 'invoiceId is required' });
  }

  if (!recipientEmail || !/^\S+@\S+\.\S+$/.test(recipientEmail)) {
    return res.status(400).send({ message: 'A valid recipientEmail is required' });
  }

  const invoice = await InvoicesDBApi.findBy({ id: invoiceId });

  if (!invoice) {
    return res.status(404).send({ message: 'Invoice not found' });
  }

  const invoiceNumber = invoice.invoice_number || invoice.reference || invoice.id;
  const amount = invoice.amount_due || invoice.total || 0;
  const currencyCode = invoice.currency?.code || 'ZAR';
  const subject = `Qweli invoice collaboration: ${invoiceNumber}`;
  const html = async () => `
    <div style="font-family: Arial, sans-serif; color: #071B2C; line-height: 1.6;">
      <h2 style="margin-bottom: 8px;">Qweli invoice collaboration</h2>
      <p>You have been invited to review invoice <strong>${escapeHtml(invoiceNumber)}</strong>.</p>
      <ul>
        <li><strong>Status:</strong> ${escapeHtml(invoice.status || 'draft')}</li>
        <li><strong>Workflow stage:</strong> ${escapeHtml(workflowStage || 'draft_review')}</li>
        <li><strong>Amount due:</strong> ${escapeHtml(currencyCode)} ${escapeHtml(amount)}</li>
      </ul>
      ${note ? `<p><strong>Team note:</strong><br/>${escapeHtml(note)}</p>` : ''}
      ${sourceUrl ? `<p><a href="${escapeHtml(sourceUrl)}">Open invoice in Qweli</a></p>` : ''}
      <p style="font-size: 12px; color: #64748B;">Sent from Qweli Accounting Suite.</p>
    </div>
  `;

  if (!EmailSender.isConfigured) {
    return res.status(200).send({
      sent: false,
      configured: false,
      message: 'Email transport is not configured. Set EMAIL_USER and EMAIL_PASS to send production email.',
      preview: {
        to: recipientEmail,
        subject,
        invoiceNumber,
        workflowStage: workflowStage || 'draft_review',
      },
    });
  }

  const sender = new EmailSender({
    to: recipientEmail,
    subject,
    html,
  });

  const result = await sender.send();

  res.status(200).send({
    sent: true,
    configured: true,
    messageId: result.messageId,
  });
}));

router.use('/', require('../helpers').commonErrorHandler);

module.exports = router;
