import { env } from "@kk/env/server";
import nodemailer from "nodemailer";
import { EVENT, LOCATION, OPENS } from "./constants";

// ---------------------------------------------------------------------------
// Transport — singleton so a warm CF isolate reuses the open TCP connection
// ---------------------------------------------------------------------------

let _transport: nodemailer.Transporter | undefined;

function getTransport(): nodemailer.Transporter | null {
	if (_transport) return _transport;
	if (!env.SMTP_HOST || !env.SMTP_USER || !env.SMTP_PASS) {
		// Not cached — re-evaluated on every call so a cold isolate that
		// receives vars after module init can still pick them up.
		return null;
	}
	_transport = nodemailer.createTransport({
		host: env.SMTP_HOST,
		port: env.SMTP_PORT,
		secure: env.SMTP_PORT === 465,
		auth: { user: env.SMTP_USER, pass: env.SMTP_PASS },
	});
	return _transport;
}

// ---------------------------------------------------------------------------
// Logging — console.log(JSON) is the only thing visible in CF dashboard
// ---------------------------------------------------------------------------

export function emailLog(
	level: "info" | "warn" | "error",
	event: string,
	extra?: Record<string, unknown>,
): void {
	console.log(JSON.stringify({ level, event, ...extra }));
}

// ---------------------------------------------------------------------------
// HTML helpers
// ---------------------------------------------------------------------------

/** Primary or secondary CTA button */
function btn(
	href: string,
	label: string,
	variant: "primary" | "secondary" = "primary",
): string {
	const bg = variant === "primary" ? "#fff" : "rgba(255,255,255,0.15)";
	const color = variant === "primary" ? "#214e51" : "#fff";
	return `<table cellpadding="0" cellspacing="0" style="margin:0 0 16px;">
  <tr><td style="border-radius:2px;background:${bg};">
    <a href="${href}" style="display:inline-block;padding:14px 32px;font-size:16px;font-weight:600;color:${color};text-decoration:none;">${label}</a>
  </td></tr>
</table>`;
}

/** Info card — single label + value */
function card(label: string, value: string): string {
	return `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:24px 0;">
  <tr><td style="padding:20px 24px;">
    <p style="margin:0 0 8px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">${label}</p>
    <p style="margin:0;font-size:18px;color:#fff;font-weight:600;">${value}</p>
  </td></tr>
</table>`;
}

/** Payment breakdown card — renders only when totalCents > 0 */
function paymentCard(drinkCardCents: number, giftCents: number): string {
	const total = drinkCardCents + giftCents;
	if (total === 0) return "";
	return `<table width="100%" cellpadding="0" cellspacing="0" style="background:rgba(255,255,255,0.08);border-radius:4px;margin:16px 0;">
  <tr><td style="padding:20px 24px;">
    <p style="margin:0 0 12px;font-size:12px;color:rgba(255,255,255,0.5);text-transform:uppercase;letter-spacing:0.06em;">Betaling</p>
    ${drinkCardCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);">Drinkkaart: <strong style="color:#fff;">${euro(drinkCardCents)}</strong></p>` : ""}
    ${giftCents > 0 ? `<p style="margin:0 0 8px;font-size:16px;color:rgba(255,255,255,0.85);">Vrijwillige gift: <strong style="color:#fff;">${euro(giftCents)}</strong></p>` : ""}
    <p style="margin:16px 0 0;padding-top:12px;border-top:1px solid rgba(255,255,255,0.1);font-size:18px;color:#fff;font-weight:600;">Totaal: ${euro(total)}</p>
  </td></tr>
</table>`;
}

/** Shared text paragraph */
function p(text: string): string {
	return `<p style="margin:0 0 16px;font-size:16px;color:rgba(255,255,255,0.85);line-height:1.6;">${text}</p>`;
}

/** Muted footnote */
function note(html: string): string {
	return `<p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);">${html}</p>`;
}

// ---------------------------------------------------------------------------
// Email layout shell
// ---------------------------------------------------------------------------

function emailLayout(heading: string, body: string): string {
	return `<!DOCTYPE html>
<html lang="nl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <title>${heading}</title>
</head>
<body style="margin:0;padding:0;background:#f4f4f5;font-family:sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4f4f5;padding:40px 0;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background:#214e51;border-radius:4px;overflow:hidden;">
        <tr><td style="padding:40px 48px 32px;">
          <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.5);letter-spacing:0.08em;text-transform:uppercase;">Kunstenkamp</p>
          <h1 style="margin:12px 0 0;font-size:28px;color:#fff;font-weight:700;">${heading}</h1>
        </td></tr>
        <tr><td style="padding:0 48px 32px;">${body}</td></tr>
        <tr><td style="padding:24px 48px;border-top:1px solid rgba(255,255,255,0.1);">
          <p style="margin:0;font-size:13px;color:rgba(255,255,255,0.4);line-height:1.6;">
            Vragen? Mail ons op <a href="mailto:info@kunstenkamp.be" style="color:rgba(255,255,255,0.6);">info@kunstenkamp.be</a><br/>
            Kunstenkamp vzw — Een initiatief voor en door kunstenaars.
          </p>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body>
</html>`;
}

// ---------------------------------------------------------------------------
// Shared send helper — logs attempt/sent/error, skips when SMTP not configured
// ---------------------------------------------------------------------------

async function send(
	type: string,
	to: string,
	subject: string,
	html: string,
): Promise<void> {
	emailLog("info", "email.attempt", { type, to });
	const transport = getTransport();
	if (!transport) {
		emailLog("warn", "email.skipped", {
			type,
			to,
			reason: "smtp_not_configured",
			// Which vars are missing — helps diagnose CF env issues
			hasHost: !!env.SMTP_HOST,
			hasUser: !!env.SMTP_USER,
			hasPass: !!env.SMTP_PASS,
		});
		return;
	}
	try {
		await transport.sendMail({ from: env.SMTP_FROM, to, subject, html });
		emailLog("info", "email.sent", { type, to });
	} catch (err) {
		emailLog("error", "email.error", { type, to, error: String(err) });
		throw err;
	}
}

// ---------------------------------------------------------------------------
// Euro formatter
// ---------------------------------------------------------------------------

function euro(cents: number): string {
	return `€${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2).replace(".", ",")}`;
}

// ---------------------------------------------------------------------------
// Helpers for registration emails
// ---------------------------------------------------------------------------

function roleLabel(wantsToPerform: boolean, artForm?: string | null): string {
	return wantsToPerform
		? `Optreden${artForm ? ` — ${artForm}` : ""}`
		: "Toeschouwer";
}

function manageUrl(token: string): string {
	return `${env.BETTER_AUTH_URL}/manage/${token}`;
}

// ---------------------------------------------------------------------------
// Emails
// ---------------------------------------------------------------------------

export async function sendConfirmationEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
	signupUrl?: string;
}) {
	const manage = manageUrl(params.managementToken);
	const signup =
		params.signupUrl ??
		`${env.BETTER_AUTH_URL}/login?signup=1&email=${encodeURIComponent(params.to)}&next=/account`;
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const giftCents = params.giftAmount ?? 0;

	await send(
		"registrationConfirmation",
		params.to,
		"Bevestiging inschrijving — Open Mic Night",
		emailLayout(
			"Je inschrijving is bevestigd!",
			p(`Hoi ${params.firstName},`) +
				p(
					`We hebben je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> in goede orde ontvangen.`,
				) +
				card("Locatie", LOCATION) +
				card("Jouw rol", roleLabel(params.wantsToPerform, params.artForm)) +
				paymentCard(drinkCardCents, giftCents) +
				p(
					"Maak een account aan om je inschrijving te beheren en je Drinkkaart te activeren.",
				) +
				btn(signup, "Account aanmaken") +
				p(
					"Wil je je gegevens aanpassen of je inschrijving annuleren? De link hieronder is uniek voor jou — deel hem niet.",
				) +
				btn(manage, "Beheer mijn inschrijving", "secondary") +
				note(
					`Of kopieer: <span style="color:rgba(255,255,255,0.6);">${manage}</span>`,
				),
		),
	);
}

export async function sendUpdateEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	wantsToPerform: boolean;
	artForm?: string | null;
	giftAmount?: number;
	drinkCardValue?: number;
}) {
	const manage = manageUrl(params.managementToken);
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const giftCents = params.giftAmount ?? 0;

	await send(
		"updateConfirmation",
		params.to,
		"Inschrijving bijgewerkt — Open Mic Night",
		emailLayout(
			"Inschrijving bijgewerkt",
			p(`Hoi ${params.firstName},`) +
				p(
					`Je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> is succesvol bijgewerkt.`,
				) +
				card("Locatie", LOCATION) +
				card("Jouw rol", roleLabel(params.wantsToPerform, params.artForm)) +
				paymentCard(drinkCardCents, giftCents) +
				btn(manage, "Bekijk mijn inschrijving"),
		),
	);
}

export async function sendCancellationEmail(params: {
	to: string;
	firstName: string;
}) {
	await send(
		"cancellation",
		params.to,
		"Inschrijving geannuleerd — Open Mic Night",
		emailLayout(
			"Inschrijving geannuleerd",
			p(`Hoi ${params.firstName},`) +
				p(
					`Je inschrijving voor <strong style="color:#fff;">${EVENT}</strong> is geannuleerd.`,
				) +
				p(
					`Van gedachten veranderd? Je kunt je altijd opnieuw inschrijven via <a href="${env.BETTER_AUTH_URL}/#registration" style="color:#fff;">kunstenkamp.be</a>.`,
				),
		),
	);
}

export async function sendSubscriptionConfirmationEmail(params: {
	to: string;
}) {
	await send(
		"subscriptionConfirmation",
		params.to,
		"Herinnering ingepland — Open Mic Night",
		emailLayout(
			"Je herinnering is ingepland!",
			p(
				`We sturen een herinnering naar <strong style="color:#fff;">${params.to}</strong> wanneer de inschrijvingen openen.`,
			) +
				card("Inschrijvingen openen", OPENS) +
				p(
					"Je ontvangt twee herinneringen: één 24 uur van tevoren en één 1 uur voor de opening.",
				) +
				p("Wees er snel bij — de plaatsen zijn beperkt!") +
				btn(`${env.BETTER_AUTH_URL}/#registration`, "Bekijk de pagina"),
		),
	);
}

export async function sendReminder24hEmail(params: {
	to: string;
	firstName?: string | null;
}) {
	const greeting = params.firstName ? `Hoi ${params.firstName},` : "Hoi!";

	await send(
		"reminder24h",
		params.to,
		"Nog 24 uur — inschrijvingen openen morgen!",
		emailLayout(
			"Nog 24 uur!",
			p(greeting) +
				p(
					`Morgen openen de inschrijvingen voor <strong style="color:#fff;">${EVENT}</strong>. Zet je wekker!`,
				) +
				card("Inschrijvingen openen", OPENS) +
				p("Wees er snel bij — de plaatsen zijn beperkt!") +
				btn(`${env.BETTER_AUTH_URL}/#registration`, "Bekijk de pagina") +
				note(
					"Je ontvangt dit bericht omdat je een herinnering hebt aangevraagd op kunstenkamp.be.",
				),
		),
	);
}

export async function sendReminderEmail(params: {
	to: string;
	firstName?: string | null;
}) {
	const greeting = params.firstName ? `Hoi ${params.firstName},` : "Hoi!";

	await send(
		"reminder1h",
		params.to,
		"Nog 1 uur — inschrijvingen openen straks!",
		emailLayout(
			"Nog 1 uur!",
			p(greeting) +
				p(
					`Over ongeveer <strong style="color:#fff;">1 uur</strong> openen de inschrijvingen voor <strong style="color:#fff;">${EVENT}</strong>.`,
				) +
				card("Inschrijvingen openen", OPENS) +
				p("Wees er snel bij — de plaatsen zijn beperkt!") +
				btn(`${env.BETTER_AUTH_URL}/#registration`, "Schrijf je in") +
				note(
					"Je ontvangt dit bericht omdat je een herinnering hebt aangevraagd op kunstenkamp.be.",
				),
		),
	);
}

export async function sendPaymentReminderEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	drinkCardValue?: number;
	giftAmount?: number;
}) {
	const manage = manageUrl(params.managementToken);
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const giftCents = params.giftAmount ?? 0;
	const total = drinkCardCents + giftCents;
	const amountNote =
		total > 0
			? `Je betaling van <strong style="color:#fff;">${euro(total)}</strong> staat nog open.`
			: "Je betaling staat nog open.";

	await send(
		"paymentReminder",
		params.to,
		"Herinnering: betaling open — Open Mic Night",
		emailLayout(
			"Betaling nog open",
			p(`Hoi ${params.firstName},`) +
				p(
					`Je hebt je ingeschreven voor <strong style="color:#fff;">${EVENT}</strong>, maar we hebben nog geen betaling ontvangen.`,
				) +
				card("Locatie", LOCATION) +
				p(`${amountNote} Log in op je account om te betalen.`) +
				btn(`${env.BETTER_AUTH_URL}/account`, "Betaal nu") +
				note(
					`Je inschrijving beheren? <a href="${manage}" style="color:rgba(255,255,255,0.6);">Klik hier</a>`,
				),
		),
	);
}

export async function sendPaymentConfirmationEmail(params: {
	to: string;
	firstName: string;
	managementToken: string;
	drinkCardValue?: number;
	giftAmount?: number;
}) {
	const manage = manageUrl(params.managementToken);
	const drinkCardCents = (params.drinkCardValue ?? 0) * 100;
	const giftCents = params.giftAmount ?? 0;

	await send(
		"paymentConfirmation",
		params.to,
		"Betaling ontvangen — Open Mic Night",
		emailLayout(
			"Betaling ontvangen!",
			p(`Hoi ${params.firstName},`) +
				p(
					`We hebben je betaling voor <strong style="color:#fff;">${EVENT}</strong> in goede orde ontvangen. Tot dan!`,
				) +
				card("Locatie", LOCATION) +
				paymentCard(drinkCardCents, giftCents) +
				btn(manage, "Beheer mijn inschrijving", "secondary"),
		),
	);
}
