import { Resend } from 'resend';

import { UserMessageDto } from './userMessages';

/** Minimal HTML escaping for user-supplied values dropped into the email body. */
function escapeHtml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

/**
 * Sends the moderator notification for a contribute-form submission.
 *
 * Best-effort and decoupled from persistence on purpose: it fires regardless of
 * whether the backend save succeeded, and reports that save status in the body —
 * so even if the DB write later fails, the submission is never lost (staff can
 * re-enter it from the email). Returns true only if an email actually went out.
 */
export async function sendContributeNotification(
  dto: UserMessageDto,
  saved: boolean
): Promise<boolean> {
  const apiKey = process.env.RESEND_API_KEY;
  const from = process.env.CONTRIBUTE_NOTIFY_FROM;
  const toRaw = process.env.CONTRIBUTE_NOTIFY_TO;

  if (!apiKey || !from || !toRaw) {
    console.warn(
      'Contribute notification skipped: missing RESEND_API_KEY / CONTRIBUTE_NOTIFY_FROM / CONTRIBUTE_NOTIFY_TO'
    );
    return false;
  }

  const to = toRaw
    .split(',')
    .map((address) => address.trim())
    .filter(Boolean);

  if (to.length === 0) return false;

  const baseUrl = (process.env.NEXT_PUBLIC_BASE_URL ?? '').replace(/\/$/, '');
  const recordLink = baseUrl ? `${baseUrl}/alkotas/${dto.rowId}` : null;

  const statusLabel = saved
    ? 'elmentve az adatbázisba'
    : '⚠ NEM sikerült menteni — kézi rögzítés szükséges';

  const subject = saved
    ? `[A-Z OPUS] Új beküldés – ${dto.messageType} #${dto.rowId}`
    : `[A-Z OPUS] ⚠ Mentés sikertelen – ${dto.messageType} #${dto.rowId}`;

  const lines = [
    `Típus: ${dto.messageType}`,
    `Rekord azonosító: ${dto.rowId}`,
    `Mentés állapota: ${statusLabel}`,
    `Beküldő e-mail: ${dto.email}`,
    recordLink ? `Adatlap: ${recordLink}` : null,
    '',
    'Üzenet:',
    dto.message,
  ].filter(Boolean);

  const html = `
    <div style="font-family: system-ui, sans-serif; font-size: 14px; line-height: 1.6;">
      <table style="border-collapse: collapse;">
        <tr><td style="padding: 2px 12px 2px 0; color: #666;">Típus</td><td><strong>${escapeHtml(String(dto.messageType))}</strong></td></tr>
        <tr><td style="padding: 2px 12px 2px 0; color: #666;">Rekord azonosító</td><td><strong>${escapeHtml(String(dto.rowId))}</strong></td></tr>
        <tr><td style="padding: 2px 12px 2px 0; color: #666;">Mentés állapota</td><td><strong>${escapeHtml(statusLabel)}</strong></td></tr>
        <tr><td style="padding: 2px 12px 2px 0; color: #666;">Beküldő e-mail</td><td><a href="mailto:${escapeHtml(dto.email)}">${escapeHtml(dto.email)}</a></td></tr>
        ${recordLink ? `<tr><td style="padding: 2px 12px 2px 0; color: #666;">Adatlap</td><td><a href="${escapeHtml(recordLink)}">${escapeHtml(recordLink)}</a></td></tr>` : ''}
      </table>
      <p style="margin: 16px 0 4px; color: #666;">Üzenet:</p>
      <div style="white-space: pre-wrap; padding: 12px; background: #f5f5f5; border-radius: 6px;">${escapeHtml(dto.message)}</div>
    </div>
  `;

  try {
    const resend = new Resend(apiKey);
    const { error } = await resend.emails.send({
      from,
      to,
      replyTo: dto.email,
      subject,
      text: lines.join('\n'),
      html,
    });

    if (error) {
      console.error('Resend contribute notification error:', error);
      return false;
    }

    return true;
  } catch (error) {
    console.error('Failed to send contribute notification:', error);
    return false;
  }
}
