import { COOKIE_NAME } from "@shared/const";
import { getSessionCookieOptions } from "./_core/cookies";
import { systemRouter } from "./_core/systemRouter";
import { publicProcedure, router } from "./_core/trpc";
import nodemailer from "nodemailer";
import { z } from "zod";

// ── SMTP Transporter ──────────────────────────────────────────────────────────
function createTransporter() {
  const host = process.env.SMTP_HOST;
  const port = parseInt(process.env.SMTP_PORT ?? "465", 10);
  const user = process.env.SMTP_USER;
  const pass = process.env.SMTP_PASS;

  if (!host || !user || !pass) {
    throw new Error("SMTP configuration missing (SMTP_HOST, SMTP_USER, SMTP_PASS)");
  }

  return nodemailer.createTransport({
    host,
    port,
    secure: port === 465, // SSL for port 465
    auth: { user, pass },
    tls: {
      rejectUnauthorized: false, // allow self-signed certs common on shared hosting
    },
  });
}

// ── Contact form schema ───────────────────────────────────────────────────────
const contactSchema = z.object({
  name: z.string().min(1, "Name erforderlich").max(200),
  company: z.string().max(200).optional(),
  email: z.string().email("Ungültige E-Mail-Adresse"),
  phone: z.string().max(50).optional(),
  reviewCount: z.string().max(20).optional(),
  message: z.string().max(5000).optional(),
});

// ── Router ────────────────────────────────────────────────────────────────────
export const appRouter = router({
  system: systemRouter,

  auth: router({
    me: publicProcedure.query(opts => opts.ctx.user),
    logout: publicProcedure.mutation(({ ctx }) => {
      const cookieOptions = getSessionCookieOptions(ctx.req);
      ctx.res.clearCookie(COOKIE_NAME, { ...cookieOptions, maxAge: -1 });
      return { success: true } as const;
    }),
  }),

  contact: router({
    send: publicProcedure
      .input(contactSchema)
      .mutation(async ({ input }) => {
        const to = process.env.SMTP_TO ?? process.env.SMTP_USER;
        const from = `"StarHero24 Kontaktformular" <${process.env.SMTP_USER}>`;

        const reviewCountLabel = input.reviewCount
          ? `<strong>Anzahl Bewertungen:</strong> ${input.reviewCount}<br>`
          : "";
        const companyLabel = input.company
          ? `<strong>Unternehmen:</strong> ${input.company}<br>`
          : "";
        const phoneLabel = input.phone
          ? `<strong>Telefon:</strong> ${input.phone}<br>`
          : "";
        const messageLabel = input.message
          ? `<strong>Nachricht:</strong><br>${input.message.replace(/\n/g, "<br>")}`
          : "";

        const html = `
<!DOCTYPE html>
<html lang="de">
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; background:#f4f6f9; padding:20px;">
  <div style="max-width:600px; margin:0 auto; background:white; border-radius:8px; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.08);">
    <div style="background:#0A1628; padding:24px 32px;">
      <h1 style="color:white; margin:0; font-size:20px; font-weight:700;">
        ⭐ Neue Anfrage über StarHero24
      </h1>
    </div>
    <div style="padding:32px;">
      <p style="color:#374151; margin-bottom:20px; font-size:15px;">
        Eine neue Kontaktanfrage wurde über das Formular auf starhero24.com eingereicht:
      </p>
      <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:6px; padding:20px; font-size:14px; line-height:1.8; color:#374151;">
        <strong>Name:</strong> ${input.name}<br>
        ${companyLabel}
        <strong>E-Mail:</strong> <a href="mailto:${input.email}" style="color:#1A73E8;">${input.email}</a><br>
        ${phoneLabel}
        ${reviewCountLabel}
        ${messageLabel}
      </div>
      <div style="margin-top:24px; padding:16px; background:#EBF5FB; border-radius:6px; border-left:3px solid #1A73E8;">
        <p style="margin:0; font-size:13px; color:#1A73E8; font-weight:600;">
          Bitte innerhalb von 24 Stunden antworten – das ist Ihr Versprechen an den Kunden.
        </p>
      </div>
    </div>
    <div style="padding:16px 32px; background:#f8fafc; border-top:1px solid #e2e8f0; font-size:12px; color:#9ca3af; text-align:center;">
      StarHero24 – Professionelles Reputation Management | starhero24.com
    </div>
  </div>
</body>
</html>`;

        const text = [
          `Neue Anfrage über StarHero24`,
          ``,
          `Name: ${input.name}`,
          input.company ? `Unternehmen: ${input.company}` : "",
          `E-Mail: ${input.email}`,
          input.phone ? `Telefon: ${input.phone}` : "",
          input.reviewCount ? `Anzahl Bewertungen: ${input.reviewCount}` : "",
          input.message ? `\nNachricht:\n${input.message}` : "",
        ]
          .filter(Boolean)
          .join("\n");

        const transporter = createTransporter();

        await transporter.sendMail({
          from,
          to,
          replyTo: input.email,
          subject: `Neue Anfrage von ${input.name} – StarHero24`,
          html,
          text,
        });

        // Also send confirmation to the customer
        await transporter.sendMail({
          from,
          to: input.email,
          subject: "Ihre Anfrage bei StarHero24 – Bestätigung",
          html: `
<!DOCTYPE html>
<html lang="de">
<head><meta charset="UTF-8"></head>
<body style="font-family: Arial, sans-serif; background:#f4f6f9; padding:20px;">
  <div style="max-width:600px; margin:0 auto; background:white; border-radius:8px; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.08);">
    <div style="background:#0A1628; padding:24px 32px;">
      <h1 style="color:white; margin:0; font-size:20px; font-weight:700;">
        ⭐ Vielen Dank für Ihre Anfrage!
      </h1>
    </div>
    <div style="padding:32px;">
      <p style="color:#374151; font-size:15px; line-height:1.7;">
        Guten Tag ${input.name},<br><br>
        vielen Dank für Ihre Anfrage bei <strong>StarHero24</strong>. Wir haben Ihre Nachricht erhalten und werden uns 
        <strong>innerhalb von 24 Stunden</strong> bei Ihnen melden.
      </p>
      <p style="color:#374151; font-size:15px; line-height:1.7;">
        Bei dringenden Anliegen erreichen Sie uns auch direkt:
      </p>
      <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:6px; padding:16px; font-size:14px; color:#374151;">
        📞 <a href="tel:+4930220117981" style="color:#1A73E8;">+49 (030) 220117981</a><br>
        ✉️ <a href="mailto:kontakt@starhero24.com" style="color:#1A73E8;">kontakt@starhero24.com</a>
      </div>
      <p style="color:#6b7280; font-size:13px; margin-top:24px;">
        Mit freundlichen Grüßen,<br>
        <strong>Ihr StarHero24-Team</strong>
      </p>
    </div>
    <div style="padding:16px 32px; background:#f8fafc; border-top:1px solid #e2e8f0; font-size:12px; color:#9ca3af; text-align:center;">
      StarHero24 – Professionelles Reputation Management | starhero24.com
    </div>
  </div>
</body>
</html>`,
          text: `Guten Tag ${input.name},\n\nvielen Dank für Ihre Anfrage bei StarHero24. Wir melden uns innerhalb von 24 Stunden.\n\nBei dringenden Anliegen: +49 (030) 220117981 | kontakt@starhero24.com\n\nMit freundlichen Grüßen,\nIhr StarHero24-Team`,
        });

        return { success: true };
      }),
  }),
});

export type AppRouter = typeof appRouter;
