// Notification email sent when a user is invited to a portfolio.
//
// Two modes:
//   "existing-user" — recipient already has an Ara account; the membership was
//   written directly, the email is just an FYI with a link to the portfolio.
//   "new-user" — recipient has no account; a pending portfolio_invitations row
//   was written. They need to sign in (which creates the user and triggers the
//   signIn callback that applies the invitation).

import { createTransport } from "nodemailer";
import { buildMailHeaders } from "./buildMailHeaders";

export type InvitationMode = "existing-user" | "new-user";

export async function PortfolioInvitationEmail({
  identifier,
  portfolioName,
  inviterName,
  linkUrl,
  mode,
}: {
  identifier: string;
  portfolioName: string;
  inviterName: string;
  linkUrl: string;
  mode: InvitationMode;
}): Promise<{ messageId: string }> {
  const from = process.env.EMAIL_FROM!;
  const transport = createTransport({
    host: process.env.EMAIL_SERVER_HOST,
    port: Number(process.env.EMAIL_SERVER_PORT),
    auth: {
      user: process.env.EMAIL_SERVER_USER,
      pass: process.env.EMAIL_SERVER_PASSWORD,
    },
  });

  const parsed = new URL(linkUrl);
  const host = parsed.host;
  const logoUrl = `${parsed.origin}/domna-email-logo.png`;

  const subject = `${inviterName} invited you to join ${portfolioName} on Ara`;
  const ctaLabel = "Sign in to Ara";

  const result = await transport.sendMail({
    to: identifier,
    from,
    subject,
    text: plainText({
      portfolioName,
      inviterName,
      linkUrl,
      ctaLabel,
      mode,
    }),
    html: domnaHtml({
      portfolioName,
      inviterName,
      linkUrl,
      ctaLabel,
      mode,
      logoUrl,
      host,
    }),
    headers: buildMailHeaders({
      fromAddress: from,
      sesConfigurationSet: process.env.SES_CONFIGURATION_SET,
    }),
  });

  const failed = result.rejected.filter(Boolean);
  if (failed.length) {
    throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`);
  }

  return { messageId: result.messageId };
}

function domnaHtml({
  portfolioName,
  inviterName,
  linkUrl,
  ctaLabel,
  mode,
  logoUrl,
  host,
}: {
  portfolioName: string;
  inviterName: string;
  linkUrl: string;
  ctaLabel: string;
  mode: InvitationMode;
  logoUrl: string;
  host: string;
}) {
  const escapedHost = host.replace(/\./g, "&#8203;.");
  const brandColor = "#14163d";
  const accentColor = "#2d348f";
  const brown = "#c4a47c";
  const background = "#F9F9F9";

  const heading = `${inviterName} invited you to ${portfolioName}`;
  const explainer =
    mode === "existing-user"
      ? `${inviterName} invited you to the <strong>${portfolioName}</strong> portfolio on Ara. Sign in and accept the invitation from your profile menu to start collaborating.`
      : `${inviterName} invited you to join the <strong>${portfolioName}</strong> portfolio on Ara. Sign in with this email address to create your account, then accept the invitation from your profile menu.`;

  return `
  <body style="background: ${background}; font-family: Helvetica, Arial, sans-serif; margin: 0; padding: 0;">
    <table width="100%" border="0" cellspacing="0" cellpadding="0"
      style="max-width: 600px; margin: 40px auto; background: #fff; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <tr>
        <td align="center" style="background: linear-gradient(90deg, ${brandColor}, ${accentColor}); padding: 12px 8px;">
          <img src="${logoUrl}" alt="Domna Logo" width="120" height="auto" style="margin-bottom: 4px;" />
        </td>
      </tr>
      <tr>
        <td align="center" style="padding: 28px 24px 12px; color: #333;">
          <h2 style="color: ${brandColor}; font-size: 22px; margin: 0 0 12px;">${heading}</h2>
          <p style="font-size: 15px; line-height: 1.5; color: #555; margin: 0 0 24px;">${explainer}</p>
          <a href="${linkUrl}" target="_blank"
            style="display: inline-block; padding: 12px 24px; background: ${brown}; color: #fff; text-decoration: none; border-radius: 6px; font-weight: 600; font-size: 15px;">
            ${ctaLabel}
          </a>
          <p style="margin-top: 28px; font-size: 13px; color: #777;">
            If you weren't expecting this email, you can safely ignore it.
          </p>
        </td>
      </tr>
      <tr>
        <td align="center" style="padding: 20px; font-size: 12px; color: #999; border-top: 1px solid #eee;">
          &copy; ${new Date().getFullYear()} Domna Homes • <span style="color: ${accentColor};">${escapedHost}</span>
        </td>
      </tr>
    </table>
  </body>
  `;
}

function plainText({
  portfolioName,
  inviterName,
  linkUrl,
  ctaLabel,
  mode,
}: {
  portfolioName: string;
  inviterName: string;
  linkUrl: string;
  ctaLabel: string;
  mode: InvitationMode;
}) {
  const heading = `${inviterName} invited you to ${portfolioName}`;
  const explainer =
    mode === "existing-user"
      ? `${inviterName} invited you to the ${portfolioName} portfolio on Ara. Sign in and accept from your profile menu to start collaborating.`
      : `${inviterName} invited you to join the ${portfolioName} portfolio on Ara. Sign in with this email to create your account, then accept from your profile menu.`;

  return `${heading}

${explainer}

${ctaLabel}: ${linkUrl}

If you weren't expecting this email, you can safely ignore it.
`;
}
