/**
 * Services d'email
 * Construction et formatage des emails
 */

/**
 * Échappe les caractères HTML pour éviter les injections
 */
export const escapeHtml = (value: string): string => {
  return value.replace(/[&<>"']/g, (char) => {
    switch (char) {
      case "&":
        return "&amp;";
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case '"':
        return "&quot;";
      case "'":
        return "&#39;";
      default:
        return char;
    }
  });
};

/**
 * Construit l'email de réinitialisation de mot de passe
 */
export const buildResetEmail = (payload: {
  email: string;
  token: string;
  appUrl?: string;
  fromName?: string;
}): { subject: string; text: string; html: string } => {
  const safeAppUrl = payload.appUrl?.replace(/\/$/, "");
  const resetLink = safeAppUrl
    ? `${safeAppUrl}/reset-password?token=${payload.token}`
    : undefined;
  const greeting = payload.fromName
    ? `Equipe ${payload.fromName}`
    : "L'equipe RollerLogic";
  const subject = "Reinitialisation de mot de passe";
  const textLines = [
    "Bonjour,",
    "",
    "Une demande de reinitialisation de mot de passe a ete effectuee.",
    resetLink ? `Lien: ${resetLink}` : undefined,
    `Token: ${payload.token}`,
    "",
    "Si vous n'etes pas a l'origine de cette demande, ignorez cet email.",
    "",
    greeting,
  ].filter(Boolean) as string[];
  const html = `
    <p>Bonjour,</p>
    <p>Une demande de reinitialisation de mot de passe a ete effectuee.</p>
    ${
      resetLink
        ? `<p><a href="${resetLink}">Reinitialiser le mot de passe</a></p>`
        : ""
    }
    <p>Token: <strong>${payload.token}</strong></p>
    <p>Si vous n'etes pas a l'origine de cette demande, ignorez cet email.</p>
    <p>${greeting}</p>
  `;
  return { subject, text: textLines.join("\n"), html };
};

/**
 * Construit l'email de vérification d'adresse
 */
export const buildVerificationEmail = (payload: {
  email: string;
  token: string;
  verifyUrl: string;
  fromName?: string;
}): { subject: string; text: string; html: string } => {
  const greeting = payload.fromName
    ? `Equipe ${payload.fromName}`
    : "L'equipe RollerLogic";
  const subject = "Verification de votre adresse email";
  const textLines = [
    "Bonjour,",
    "",
    "Merci pour votre inscription sur RollerLogic.",
    "Cliquez sur ce lien pour valider votre email :",
    payload.verifyUrl,
    "",
    `Token: ${payload.token}`,
    "",
    "Si vous n'etes pas a l'origine de cette inscription, ignorez cet email.",
    "",
    greeting,
  ];
  const html = `
    <p>Bonjour,</p>
    <p>Merci pour votre inscription sur RollerLogic.</p>
    <p><a href="${payload.verifyUrl}">Valider mon adresse email</a></p>
    <p>Token: <strong>${payload.token}</strong></p>
    <p>Si vous n'etes pas a l'origine de cette inscription, ignorez cet email.</p>
    <p>${greeting}</p>
  `;
  return { subject, text: textLines.join("\n"), html };
};

/**
 * Construit l'email de contact
 */
export const buildContactEmail = (payload: {
  userId: number;
  email: string;
  displayName: string;
  subject?: string;
  message: string;
  ip?: string | null;
  userAgent?: string | null;
}): { subject: string; text: string; html: string } => {
  const safeSubject = payload.subject?.trim() || "Contact RollerLogic";
  const now = new Date();
  const dateStr = now.toLocaleDateString("fr-FR", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });

  const textLines = [
    "Nouveau message de contact RollerLogic",
    "",
    `Utilisateur: ${payload.displayName} <${payload.email}>`,
    `UserId: ${payload.userId}`,
    payload.ip ? `IP: ${payload.ip}` : undefined,
    payload.userAgent ? `User-Agent: ${payload.userAgent}` : undefined,
    "",
    `Sujet: ${safeSubject}`,
    "",
    "Message:",
    payload.message,
  ].filter(Boolean) as string[];

  const html = `
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; background-color: #0a0f1a;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background-color: #0a0f1a; padding: 40px 20px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="max-width: 600px; background: linear-gradient(145deg, #111827, #1f2937); border-radius: 16px; overflow: hidden; box-shadow: 0 20px 40px rgba(0,0,0,0.4);">
          <!-- Header -->
          <tr>
            <td style="background: linear-gradient(135deg, #ffb300, #ff8c00); padding: 30px 40px; text-align: center;">
              <h1 style="margin: 0; font-size: 24px; color: #ffffff; font-weight: 700; text-shadow: 0 1px 2px rgba(0,0,0,0.3);">
                📬 Nouveau message de contact
              </h1>
              <p style="margin: 8px 0 0; font-size: 14px; color: rgba(255,255,255,0.9);">
                RollerLogic - Support
              </p>
            </td>
          </tr>
          
          <!-- User Info -->
          <tr>
            <td style="padding: 30px 40px 20px;">
              <table width="100%" cellpadding="0" cellspacing="0" style="background: rgba(45, 226, 196, 0.1); border: 1px solid rgba(45, 226, 196, 0.3); border-radius: 12px; padding: 20px;">
                <tr>
                  <td>
                    <p style="margin: 0 0 12px; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #2de2c4; font-weight: 600;">
                      Expéditeur
                    </p>
                    <p style="margin: 0 0 8px; font-size: 18px; color: #fff; font-weight: 600;">
                      ${escapeHtml(payload.displayName)}
                    </p>
                    <p style="margin: 0; font-size: 14px; color: #9ca3af;">
                      <a href="mailto:${escapeHtml(payload.email)}" style="color: #60a5fa; text-decoration: none;">
                        ${escapeHtml(payload.email)}
                      </a>
                    </p>
                    <p style="margin: 8px 0 0; font-size: 12px; color: #6b7280;">
                      ID: #${payload.userId}
                    </p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          
          <!-- Subject -->
          <tr>
            <td style="padding: 0 40px 20px;">
              <p style="margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #ffb300; font-weight: 600;">
                Sujet
              </p>
              <p style="margin: 0; font-size: 16px; color: #fff; font-weight: 500;">
                ${escapeHtml(safeSubject)}
              </p>
            </td>
          </tr>
          
          <!-- Message -->
          <tr>
            <td style="padding: 0 40px 30px;">
              <p style="margin: 0 0 12px; font-size: 12px; text-transform: uppercase; letter-spacing: 1px; color: #ffb300; font-weight: 600;">
                Message
              </p>
              <div style="background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.1); border-radius: 12px; padding: 20px;">
                <p style="margin: 0; font-size: 15px; color: #e5e7eb; line-height: 1.7; white-space: pre-wrap;">
${escapeHtml(payload.message)}
                </p>
              </div>
            </td>
          </tr>
          
          <!-- Metadata -->
          <tr>
            <td style="padding: 0 40px 30px;">
              <table width="100%" cellpadding="0" cellspacing="0" style="background: rgba(0,0,0,0.2); border-radius: 8px; padding: 15px;">
                <tr>
                  <td style="font-size: 11px; color: #6b7280; line-height: 1.6;">
                    <strong style="color: #9ca3af;">Date:</strong> ${dateStr}<br>
                    ${payload.ip ? `<strong style="color: #9ca3af;">IP:</strong> ${escapeHtml(payload.ip)}<br>` : ""}
                    ${payload.userAgent ? `<strong style="color: #9ca3af;">User-Agent:</strong> ${escapeHtml(payload.userAgent.slice(0, 100))}${payload.userAgent.length > 100 ? "..." : ""}` : ""}
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          
          <!-- Footer -->
          <tr>
            <td style="background: rgba(0,0,0,0.3); padding: 20px 40px; text-align: center; border-top: 1px solid rgba(255,255,255,0.1);">
              <p style="margin: 0; font-size: 12px; color: #6b7280;">
                💡 Répondez directement à cet email pour contacter l'utilisateur
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>
  `;
  return {
    subject: `[Contact] ${safeSubject}`,
    text: textLines.join("\n"),
    html,
  };
};
