/**
 * Lightweight email sender.
 * - Always logs in non-production (so local OTP works without SMTP).
 * - Sends via Resend when RESEND_API_KEY is set.
 */

type SendEmailInput = {
  to: string;
  subject: string;
  text: string;
  html?: string;
  /** When false, log failures instead of throwing (default true). */
  throwOnError?: boolean;
};

function escapeHtml(value: string) {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');
}

export function buildSimpleEmailHtml(opts: {
  title: string;
  body: string;
  ctaLabel?: string;
  ctaUrl?: string;
}) {
  const appName = process.env.NEXT_PUBLIC_APP_NAME || 'eHandyHire';
  const paragraphs = opts.body
    .split('\n')
    .filter(Boolean)
    .map((line) => `<p style="margin:0 0 12px;line-height:1.5;color:#334155">${escapeHtml(line)}</p>`)
    .join('');
  const cta =
    opts.ctaLabel && opts.ctaUrl
      ? `<p style="margin:24px 0 0"><a href="${escapeHtml(opts.ctaUrl)}" style="display:inline-block;background:#0f172a;color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-weight:600">${escapeHtml(opts.ctaLabel)}</a></p>`
      : '';

  return `<!DOCTYPE html>
<html><body style="margin:0;padding:24px;background:#f8fafc;font-family:system-ui,-apple-system,sans-serif">
  <div style="max-width:560px;margin:0 auto;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:24px">
    <p style="margin:0 0 4px;font-size:12px;font-weight:700;letter-spacing:0.08em;text-transform:uppercase;color:#94a3b8">${escapeHtml(appName)}</p>
    <h1 style="margin:0 0 16px;font-size:20px;color:#0f172a">${escapeHtml(opts.title)}</h1>
    ${paragraphs}
    ${cta}
    <p style="margin:28px 0 0;font-size:12px;color:#94a3b8">This is an automated message from ${escapeHtml(appName)}.</p>
  </div>
</body></html>`;
}

export async function sendEmail({
  to,
  subject,
  text,
  html,
  throwOnError = true,
}: SendEmailInput): Promise<void> {
  if (process.env.NODE_ENV !== 'production') {
    console.log(`📧 Email to ${to}\n   Subject: ${subject}\n   ${text}`);
  }

  const apiKey = process.env.RESEND_API_KEY?.trim();
  if (!apiKey) {
    if (process.env.NODE_ENV === 'production') {
      console.warn(`Email not sent to ${to}: RESEND_API_KEY is not configured`);
    }
    return;
  }

  const from =
    process.env.EMAIL_FROM?.trim() || 'eHandyHire <onboarding@resend.dev>';

  try {
    const res = await fetch('https://api.resend.com/emails', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        from,
        to: [to],
        subject,
        text,
        html: html || text,
      }),
    });

    if (!res.ok) {
      const body = await res.text().catch(() => '');
      console.error(`Resend email failed (${res.status}): ${body}`);
      if (throwOnError) throw new Error('Failed to send email');
    }
  } catch (err) {
    console.error('Email send error:', err);
    if (throwOnError) throw err;
  }
}
