import nodemailer from 'nodemailer'

/**
 * Email the (client-generated) Fulfillment Earnings PDF report as attachment.
 *
 * Body: {
 *   toEmail:  string (required)
 *   ccEmail?: string
 *   subject?: string
 *   message?: string (plain text, becomes the mail body)
 *   base64:   string (required — the pdfmake-generated PDF)
 *   fileName?: string
 *   dateRange?: string (cosmetic — used in default subject)
 * }
 */
const isValidEmail = (s: any) => typeof s === 'string' && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim())

const escapeHtml = (s: string) => s
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')

const buildHtml = (message: string, dateRange: string) => {
  const bodyText = escapeHtml(message || '').replace(/\n/g, '<br>')
  return `<!DOCTYPE html><html><head><meta charset="utf-8"></head>
<body style="margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:1.6;color:#333;background-color:#f4f4f4;">
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f4f4f4;"><tr><td style="padding:20px 0;">
<table role="presentation" width="600" cellspacing="0" cellpadding="0" style="margin:0 auto;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 2px 4px rgba(0,0,0,0.1);">
<tr><td style="background:#2c3e50;padding:24px 40px;"><h1 style="margin:0;color:#fff;font-size:20px;font-weight:600;">Fulfillment Earnings Report${dateRange ? ` — ${escapeHtml(dateRange)}` : ''}</h1></td></tr>
<tr><td style="padding:32px 40px;">
<p style="margin:0 0 16px 0;">${bodyText || 'Attached you\'ll find the fulfillment earnings report.'}</p>
<p style="margin:0;color:#888;font-size:12px;">Sent automatically by LogShip ERP.</p>
</td></tr>
</table></td></tr></table></body></html>`
}

export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event)
    const toEmail = String(body.toEmail || '').trim()
    const ccEmail = body.ccEmail ? String(body.ccEmail).trim() : ''
    const base64 = String(body.base64 || '')
    const dateRange = String(body.dateRange || '').trim()

    if (!isValidEmail(toEmail)) {
      return { status: 400, message: 'A valid recipient email is required' }
    }
    if (ccEmail && !isValidEmail(ccEmail)) {
      return { status: 400, message: 'CC email is not valid' }
    }
    if (!base64) {
      return { status: 400, message: 'No PDF provided' }
    }

    const fileName = String(body.fileName || '').trim() || 'fulfillment-earnings-report.pdf'
    const subject = String(body.subject || '').trim()
      || `Fulfillment Earnings Report${dateRange ? ` — ${dateRange}` : ''}`

    const transporter = nodemailer.createTransport({
      host: 'localhost', port: 25, secure: false,
      tls: { rejectUnauthorized: false }
    })

    const emailOptions: any = {
      from: 'no-reply@logyou.de',
      to: toEmail,
      subject,
      html: buildHtml(String(body.message || ''), dateRange),
      attachments: [{
        filename: fileName,
        content: Buffer.from(base64, 'base64'),
        contentType: 'application/pdf'
      }]
    }
    if (ccEmail) emailOptions.cc = ccEmail

    try {
      const info = await transporter.sendMail(emailOptions)
      return { status: 200, message: 'Report email sent', messageId: info?.messageId }
    } catch (err: any) {
      console.error('[Earnings Report Email] Send error:', err)
      return { status: 500, message: `Failed to send email: ${err.message || err}` }
    }
  } catch (err: any) {
    console.error('[Earnings Report Email] Error:', err)
    return { status: 500, message: err.message || 'Failed to send report email' }
  }
})
