import type { ContactMailInput, RepairMailInput } from "./types";

function escapeHtml(value?: string) {
  return (value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

function rows(entries: Array<[string, string | undefined]>) {
  return entries
    .filter(([, value]) => value)
    .map(([label, value]) => `<tr><th align="left" style="padding:6px 12px;border-bottom:1px solid #d9dee6;">${escapeHtml(label)}</th><td style="padding:6px 12px;border-bottom:1px solid #d9dee6;">${escapeHtml(value)}</td></tr>`)
    .join("");
}

function textRows(entries: Array<[string, string | undefined]>) {
  return entries
    .filter(([, value]) => value)
    .map(([label, value]) => `${label}: ${value}`)
    .join("\n");
}

export function contactTemplate(input: ContactMailInput) {
  const subject = `Kontaktanfrage: ${input.subject ?? "Funktechnik Schubert"}`;
  const entries: Array<[string, string | undefined]> = [
    ["Datum", new Date(input.createdAt).toLocaleString("de-DE")],
    ["Name", input.name],
    ["E-Mail", input.email],
    ["Telefon", input.phone],
    ["Betreff", input.subject],
    ["Nachricht", input.message],
  ];

  return {
    subject,
    text: `Neue Kontaktanfrage\n\n${textRows(entries)}`,
    html: `<h1>Neue Kontaktanfrage</h1><table cellspacing="0" cellpadding="0">${rows(entries)}</table>`,
  };
}

export function repairTemplate(input: RepairMailInput) {
  const subject = `Reparaturanfrage: ${input.manufacturer} ${input.model}`;
  const entries: Array<[string, string | undefined]> = [
    ["Datum", new Date(input.createdAt).toLocaleString("de-DE")],
    ["Name", input.name],
    ["E-Mail", input.email],
    ["Telefon", input.phone],
    ["Hersteller", input.manufacturer],
    ["Modell", input.model],
    ["Geräteart", input.deviceType],
    ["Seriennummer", input.serialNumber],
    ["Fehlerbeschreibung", input.description],
    ["Zubehör", input.accessories],
    ["Gerät geöffnet?", input.opened],
    ["Vorarbeiten", input.previousWork],
  ];

  return {
    subject,
    text: `Neue Reparaturanfrage\n\n${textRows(entries)}`,
    html: `<h1>Neue Reparaturanfrage</h1><table cellspacing="0" cellpadding="0">${rows(entries)}</table>`,
  };
}

export function testTemplate() {
  return {
    subject: "SMTP Testmail - Funktechnik Schubert",
    text: "Diese Testmail wurde aus der Funktechnik Schubert Website-Administration gesendet.",
    html: "<h1>SMTP Testmail</h1><p>Diese Testmail wurde aus der Funktechnik Schubert Website-Administration gesendet.</p>",
  };
}
