import { createHmac } from 'crypto';

function generateOTP(secret, email, window) {
  return createHmac('sha256', secret)
    .update(`${email.toLowerCase().trim()}:${window}`)
    .digest('hex')
    .slice(0, 6)
    .toUpperCase();
}

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { email } = req.body || {};
  if (!email || !email.includes('@')) {
    return res.status(400).json({ error: 'Valid email required' });
  }

  const otpSecret = process.env.OTP_SECRET;
  const resendKey = process.env.RESEND_API_KEY;
  if (!otpSecret || !resendKey) {
    return res.status(500).json({ error: 'Server not configured' });
  }

  // 5-minute time window — stateless, no DB needed
  const window = Math.floor(Date.now() / 1000 / 300);
  const code = generateOTP(otpSecret, email, window);

  const emailResp = await fetch('https://api.resend.com/emails', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${resendKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      from: 'PULSE <noreply@pulseos.dev>',
      to: [email],
      subject: 'Your PULSE recovery code',
      html: `
        <div style="font-family:sans-serif;max-width:480px;margin:0 auto;padding:40px 24px;background:#0f172a;color:#e2e8f0;border-radius:12px;">
          <h2 style="color:#38bdf8;margin-bottom:8px;">PULSE License Recovery</h2>
          <p style="color:#94a3b8;margin-bottom:32px;">Here is your one-time recovery code. It expires in 5 minutes.</p>
          <div style="background:#1e293b;border:1px solid #334155;border-radius:8px;padding:24px;text-align:center;margin-bottom:32px;">
            <span style="font-size:36px;font-weight:700;letter-spacing:12px;color:#38bdf8;font-family:monospace;">${code}</span>
          </div>
          <p style="color:#475569;font-size:13px;">If you didn't request this, ignore this email — your key is safe.</p>
        </div>
      `,
    }),
  });

  if (!emailResp.ok) {
    const err = await emailResp.json().catch(() => ({}));
    console.error('Resend error:', err);
    return res.status(500).json({ error: 'Failed to send email. Please try again.' });
  }

  return res.status(200).json({ sent: true });
}
