let Resend;
try {
  Resend = (await import('resend')).Resend;
} catch {
  // resend not available — email features will be disabled
}

const resend = (process.env.RESEND_API_KEY && Resend) ? new Resend(process.env.RESEND_API_KEY) : null;

const FROM_EMAIL = process.env.FROM_EMAIL || 'Upfyn Code <noreply@upfyn.com>';
const APP_URL = process.env.APP_URL || 'https://cli.upfyn.com';

export async function sendPasswordResetEmail(toEmail, resetToken) {
  if (!resend) {
    console.warn('[Email] RESEND_API_KEY not set — cannot send password reset email');
    return { success: false, error: 'Email service not configured' };
  }

  const resetUrl = `${APP_URL}/reset-password?token=${resetToken}`;

  try {
    const { data, error } = await resend.emails.send({
      from: FROM_EMAIL,
      to: toEmail,
      subject: 'Reset your Upfyn Code password',
      html: `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#0f172a;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#0f172a;padding:40px 20px;">
    <tr><td align="center">
      <table width="480" cellpadding="0" cellspacing="0" style="background:#1e293b;border-radius:12px;border:1px solid #334155;overflow:hidden;">
        <tr><td style="padding:32px 32px 24px;text-align:center;">
          <h1 style="margin:0 0 8px;color:#f8fafc;font-size:22px;font-weight:600;">Password Reset</h1>
          <p style="margin:0;color:#94a3b8;font-size:14px;">You requested a password reset for your Upfyn Code account.</p>
        </td></tr>
        <tr><td style="padding:0 32px 24px;text-align:center;">
          <a href="${resetUrl}" style="display:inline-block;padding:12px 32px;background:#3b82f6;color:#fff;text-decoration:none;border-radius:8px;font-size:15px;font-weight:500;">
            Reset Password
          </a>
        </td></tr>
        <tr><td style="padding:0 32px 24px;text-align:center;">
          <p style="margin:0;color:#64748b;font-size:12px;">This link expires in 1 hour. If you didn't request this, you can safely ignore this email.</p>
        </td></tr>
        <tr><td style="padding:16px 32px;background:#0f172a;border-top:1px solid #334155;text-align:center;">
          <p style="margin:0;color:#475569;font-size:11px;">Upfyn Code &mdash; cli.upfyn.com</p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>`,
    });

    if (error) {
      console.error('[Email] Resend error:', error);
      return { success: false, error: error.message };
    }

    return { success: true, id: data?.id };
  } catch (err) {
    console.error('[Email] Send failed:', err.message);
    return { success: false, error: err.message };
  }
}
