import type { APIRoute } from "astro";
import nodemailer from "nodemailer";
import { isRateLimited, sanitize, isValidEmail } from "./contact.utils.js";

let transporter: nodemailer.Transporter | null = null;
export function _resetTransporter() { transporter = null; }

function getTransporter(): nodemailer.Transporter | null {
  if (transporter) return transporter;

  const host = process.env.SMTP_HOST || "ssl0.ovh.net";
  const port = Number.parseInt(process.env.SMTP_PORT || "465");
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASSWORD;

  if (!user || !pass) {
    console.warn("[contact] SMTP_USER ou SMTP_PASSWORD non configure - emails desactives");
    return null;
  }

  transporter = nodemailer.createTransport({
    host,
    port,
    secure: port === 465,
    auth: { user, pass },
  });

  console.log(`[contact] SMTP configure : ${user} via ${host}:${port}`);
  return transporter;
}

export const POST: APIRoute = async ({ request, clientAddress }) => {
  const headers = {
    "Content-Type": "application/json",
    "X-Content-Type-Options": "nosniff",
  };

  // Rate limit
  const ip = clientAddress || "unknown";
  if (isRateLimited(ip)) {
    return new Response(JSON.stringify({ error: "Trop de requetes. Reessayez dans quelques minutes." }), {
      status: 429,
      headers,
    });
  }

  // Parse body
  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return new Response(JSON.stringify({ error: "Corps de requete invalide." }), {
      status: 400,
      headers,
    });
  }

  // Honeypot
  if (body.website) {
    return new Response(JSON.stringify({ ok: true }), { status: 200, headers });
  }

  // Validate
  const firstName = sanitize(body.firstName);
  const lastName = sanitize(body.lastName);
  const email = sanitize(body.email);
  const company = sanitize(body.company);
  const phone = sanitize(body.phone);
  const message = sanitize(body.message);

  if (!firstName || firstName.length < 2) {
    return new Response(JSON.stringify({ error: "Prenom invalide." }), { status: 400, headers });
  }
  if (!lastName || lastName.length < 2) {
    return new Response(JSON.stringify({ error: "Nom invalide." }), { status: 400, headers });
  }
  if (!email || !isValidEmail(email)) {
    return new Response(JSON.stringify({ error: "Email invalide." }), { status: 400, headers });
  }
  if (!message || message.length < 10) {
    return new Response(JSON.stringify({ error: "Message trop court (min. 10 caracteres)." }), { status: 400, headers });
  }

  // Send email
  const t = getTransporter();
  if (!t) {
    console.error("[contact] SMTP non configure - email non envoye");
    return new Response(JSON.stringify({ error: "Service email temporairement indisponible." }), {
      status: 503,
      headers,
    });
  }

  const from = process.env.SMTP_FROM || process.env.SMTP_USER!;
  const to = process.env.CONTACT_TO || process.env.SMTP_USER!;

  try {
    await t.sendMail({
      from: `Missioflow <${from}>`,
      to,
      replyTo: email,
      subject: `[Missioflow] Demande de ${firstName} ${lastName}`,
      html: `
<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
<body style="margin:0;padding:0;background-color:#f4f4f7;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:#f4f4f7;">
    <tr><td align="center" style="padding:40px 20px;">
      <table role="presentation" width="500" cellpadding="0" cellspacing="0" style="max-width:500px;width:100%;">
        <tr><td align="center" style="padding-bottom:32px;">
          <span style="font-size:28px;font-weight:800;color:#1e293b;letter-spacing:-0.5px;">
            <span style="color:#1d4ed8;">Missio</span>flow
          </span>
        </td></tr>
        <tr><td style="background:#ffffff;border-radius:12px;padding:40px 36px;box-shadow:0 1px 3px rgba(0,0,0,0.08);">
          <h1 style="font-size:22px;font-weight:700;color:#1e293b;margin:0 0 20px 0;">
            Nouvelle demande de contact
          </h1>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
            <tr>
              <td style="padding:8px 0;font-size:14px;color:#64748b;width:120px;vertical-align:top;">Prenom</td>
              <td style="padding:8px 0;font-size:14px;color:#1e293b;font-weight:600;">${firstName}</td>
            </tr>
            <tr>
              <td style="padding:8px 0;font-size:14px;color:#64748b;vertical-align:top;">Nom</td>
              <td style="padding:8px 0;font-size:14px;color:#1e293b;font-weight:600;">${lastName}</td>
            </tr>
            <tr>
              <td style="padding:8px 0;font-size:14px;color:#64748b;vertical-align:top;">Email</td>
              <td style="padding:8px 0;font-size:14px;color:#1d4ed8;font-weight:600;">${email}</td>
            </tr>
            ${company ? `<tr>
              <td style="padding:8px 0;font-size:14px;color:#64748b;vertical-align:top;">Entreprise</td>
              <td style="padding:8px 0;font-size:14px;color:#1e293b;font-weight:600;">${company}</td>
            </tr>` : ""}
            ${phone ? `<tr>
              <td style="padding:8px 0;font-size:14px;color:#64748b;vertical-align:top;">Telephone</td>
              <td style="padding:8px 0;font-size:14px;color:#1e293b;font-weight:600;">${phone}</td>
            </tr>` : ""}
          </table>
          <hr style="border:none;border-top:1px solid #e5e7eb;margin:20px 0;">
          <h2 style="font-size:16px;font-weight:600;color:#1e293b;margin:0 0 8px 0;">Message</h2>
          <p style="font-size:15px;color:#475569;line-height:1.6;margin:0;white-space:pre-wrap;">${message}</p>
        </td></tr>
        <tr><td align="center" style="padding:24px 0 0 0;">
          <p style="font-size:12px;color:#9ca3af;margin:0;">
            Missioflow - Gestion d'interventions terrain
          </p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body></html>`,
      text: `Nouvelle demande de contact\n\nPrenom: ${firstName}\nNom: ${lastName}\nEmail: ${email}\nEntreprise: ${company || "-"}\nTelephone: ${phone || "-"}\n\nMessage:\n${message}`,
    });

    console.log(`[contact] Email envoye : ${firstName} ${lastName} <${email}>`);
    return new Response(JSON.stringify({ ok: true }), { status: 200, headers });
  } catch (err) {
    console.error(`[contact] Erreur envoi : ${(err as Error).message}`);
    return new Response(JSON.stringify({ error: "Erreur lors de l'envoi. Reessayez plus tard." }), {
      status: 500,
      headers,
    });
  }
};
