import { NextRequest, NextResponse } from 'next/server';
import { createToken } from '@/lib/verify';
import nodemailer from 'nodemailer';

export async function POST(request: NextRequest) {
  try {
    const { email } = await request.json();
    if (!email) return NextResponse.json({ error: 'Email required' }, { status: 400 });
    const token = await createToken(email, 'email_verification');
    const link = `${process.env.NEXT_PUBLIC_BASE_URL || 'http://localhost:3000'}/verify-email?token=${token}`;
    const host = process.env.SMTP_HOST;
    const user = process.env.SMTP_USER;
    const pass = process.env.SMTP_PASS;
    if (host && user && pass) {
      const transporter = nodemailer.createTransport({
        host, port: parseInt(process.env.SMTP_PORT || '587'),
        auth: { user, pass: pass.replace(/\s/g, '') },
        tls: { rejectUnauthorized: false }
      });
      await transporter.sendMail({
        from: `"Marich Wellness" <${process.env.EMAIL_FROM || user}>`,
        to: email,
        subject: 'Verify your email - Marich Wellness',
        text: `Click this link to verify: ${link}\n\nExpires in 5 minutes.`,
        html: `<div style="font-family:sans-serif;padding:40px;background:#f9fafb">
          <div style="background:#064e3b;color:white;padding:24px;text-align:center">
            <h1 style="margin:0">Marich Wellness</h1>
            <p style="margin:8px 0 0;opacity:0.9">Verify your email</p>
          </div>
          <div style="padding:40px;text-align:center;background:white">
            <a href="${link}" style="display:inline-block;padding:16px 40px;background:#064e3b;color:white;text-decoration:none;font-weight:bold">Verify Email</a>
            <p style="color:#6b7280;font-size:14px">Link expires in 5 minutes</p>
          </div>
        </div>`
      });
    }
    return NextResponse.json({ success: true, message: 'Verification email sent' });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}