import nodemailer from 'nodemailer';

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

  try {
    const { name, email, message } = req.body;

    // Prüfe ob SMTP konfiguriert ist
    if (!process.env.SMTP_HOST || !process.env.SMTP_USER || !process.env.SMTP_PASSWORD) {
      console.log('SMTP not configured, logging message instead:', { name, email, message });
      return res.status(200).json({ 
        message: 'Message logged (SMTP not configured)',
        debug: { name, email, message }
      });
    }

    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: Number(process.env.SMTP_PORT) || 587,
      secure: Number(process.env.SMTP_PORT) === 465,
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD,
      },
    });

    await transporter.sendMail({
      from: `"${name}" <${email}>`,
      to: 'kontakt@pixelbrew.de', // Zieladresse anpassen, falls gewünscht
      subject: `Neue Kontaktanfrage von ${name}`,
      text: `
Name: ${name}
Email: ${email}

Nachricht:
${message}
      `,
      html: `
        <p><b>Name:</b> ${name}</p>
        <p><b>Email:</b> ${email}</p>
        <p><b>Nachricht:</b><br/>${message.replace(/\n/g, '<br/>')}</p>
      `,
    });

    res.status(200).json({ message: 'Email sent successfully' });
  } catch (error) {
    console.error('Error sending email:', error);
    res.status(500).json({ message: 'Error sending email' });
  }
}
