import nodemailer from "nodemailer";

const rateLimitMap = new Map();
const RATE_LIMIT_WINDOW = 60000; 
const MAX_REQUESTS = 3; 

function checkRateLimit(ip) {
	const now = Date.now();
	const userRequests = rateLimitMap.get(ip) || [];

	const recentRequests = userRequests.filter((time) => now - time < RATE_LIMIT_WINDOW);

	if (recentRequests.length >= MAX_REQUESTS) {
		return false;
	}

	recentRequests.push(now);
	rateLimitMap.set(ip, recentRequests);
	return true;
}

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

	try {

		const ip =
			req.headers["x-forwarded-for"] || req.headers["x-real-ip"] || req.socket.remoteAddress || "unknown";
		if (!checkRateLimit(ip)) {
			return res.status(429).json({
				error: "Prea multe cereri. Te rugăm să aștepți un minut.",
			});
		}

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

		if (!name || !email || !message) {
			return res.status(400).json({
				error: "Toate câmpurile sunt obligatorii",
			});
		}

		if (name.length > 100 || email.length > 100 || message.length > 2000) {
			return res.status(400).json({
				error: "Datele introduse sunt prea lungi",
			});
		}

		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			return res.status(400).json({
				error: "Email invalid",
			});
		}

		const sanitizedName = name.replace(/[<>]/g, "");
		const sanitizedMessage = message.replace(/[<>]/g, "");

		const transporter = nodemailer.createTransport({
			host: 'mail.emagyl.ro',
			port: 465,
			secure: "465", 
			auth: {
				user: 'contact@emagyl.ro',
				pass: 'Denis1234!@',
			},
		});

		await transporter.verify();

		await transporter.sendMail({
			from: `"Website Contact" <contact@emagyl.ro>`,
			to: "contact@emagyl.ro",
			replyTo: email,
			subject: `Mesaj nou de la ${sanitizedName}`,
			html: `
                    <!DOCTYPE html>
                    <html>
                    <head>
                         <style>
                              body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
                              .container { max-width: 600px; margin: 0 auto; padding: 20px; }
                              .header { background-color: #f4f4f4; padding: 20px; border-radius: 5px; }
                              .content { padding: 20px 0; }
                              .field { margin-bottom: 15px; }
                              .label { font-weight: bold; color: #555; }
                              .message-box { background-color: #f9f9f9; padding: 15px; border-left: 4px solid #007bff; margin-top: 10px; }
                         </style>
                    </head>
                    <body>
                         <div class="container">
                              <div class="header">
                                   <h2 style="margin: 0; color: #007bff;">📧 Mesaj nou din formularul de contact</h2>
                              </div>
                              <div class="content">
                                   <div class="field">
                                        <span class="label">Nume:</span> ${sanitizedName}
                                   </div>
                                   <div class="field">
                                        <span class="label">Email:</span> <a href="mailto:${email}">${email}</a>
                                   </div>
                                   <div class="field">
                                        <span class="label">Mesaj:</span>
                                        <div class="message-box">
                                             ${sanitizedMessage.replace(/\n/g, "<br>")}
                                        </div>
                                   </div>
                              </div>
                         </div>
                    </body>
                    </html>
               `,
			text: `
Mesaj nou din formularul de contact

Nume: ${sanitizedName}
Email: ${email}

Mesaj:
${sanitizedMessage}
               `,
		});

		return res.status(200).json({
			success: true,
			message: "Email trimis cu succes!",
		});
	} catch (error) {
		console.error("Error sending email:", error);
		return res.status(500).json({
			error: "Eroare la trimiterea emailului. Te rugăm să reîncerci.",
		});
	}
}
