import {
  type TAttachmentExportFailureReason,
  type TRetentionNoticeArchivedSurvey,
  type TRetentionNoticeResponseDeletion,
  renderAccountDeletedEmail,
  renderAccountDeletionEmail,
  renderAttachmentExportFailedEmail,
  renderAttachmentExportReadyEmail,
  renderEmailCustomizationPreviewEmail,
  renderEmbedSurveyPreviewEmail,
  renderForgotPasswordEmail,
  renderInviteAcceptedEmail,
  renderInviteEmail,
  renderLinkSurveyEmail,
  renderMemberRetentionNoticeEmail,
  renderNewEmailVerification,
  renderPasswordResetNotifyEmail,
  renderResponseFinishedEmail,
  renderSsoRecoveryFactorsRemovedEmail,
  renderSsoSignInHintEmail,
  renderSurveyRetentionNoticeEmail,
  renderVerificationEmail,
} from "@formbricks/email";
import { TEmailTemplateLegalProps } from "@formbricks/email/src/types/email";
import { logger } from "@formbricks/logger";
import type { TLinkSurveyEmailData } from "@formbricks/types/email";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import type { TResponse } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { TUserEmail, TUserLocale } from "@formbricks/types/user";
import { IMPRINT_ADDRESS, IMPRINT_URL, MAIL_FROM, PRIVACY_URL, TERMS_URL, WEBAPP_URL } from "@/lib/constants";
import { getPublicDomain } from "@/lib/getPublicUrl";
import {
  createEmailChangeToken,
  createEmailToken,
  createInviteToken,
  createToken,
  createTokenForLinkSurvey,
} from "@/lib/jwt";
import { getOrganizationByWorkspaceId } from "@/lib/organization/service";
import { TElementResponseMappingSurvey, getElementResponseMapping } from "@/lib/responses";
import { getTranslate } from "@/lingodotdev/server";
import {
  TVerificationRequestPurpose,
  VERIFICATION_LINK_TTL_SECONDS,
  buildVerificationLinks,
} from "@/modules/auth/lib/verification-links";
import { toEmailDisplayText } from "@/modules/email/lib/email-display-text";
import type { TEmailRateLimitContext } from "@/modules/email/lib/email-rate-limits";
import { sendEmail } from "@/modules/email/lib/send-email";
import { buildVerifiedLinkSurveyUrl } from "@/modules/email/lib/verified-link-survey-url";
import { resolveStorageUrl } from "@/modules/storage/utils";

export { IS_SMTP_CONFIGURED } from "@/lib/constants";
export type { TAttachmentExportFailureReason };
export { sendEmail } from "@/modules/email/lib/send-email";

const legalProps: TEmailTemplateLegalProps = {
  privacyUrl: PRIVACY_URL || undefined,
  termsUrl: TERMS_URL || undefined,
  imprintUrl: IMPRINT_URL || undefined,
  imprintAddress: IMPRINT_ADDRESS || undefined,
};

export type TResponseFinishedEmailSurvey = TElementResponseMappingSurvey &
  // `variables` / `hiddenFields` are the resolver's fallback; `embeddedFields` carries the joined
  // EmbeddedData rows the template resolves definitions through (ENG-1837).
  Pick<TSurvey, "id" | "name" | "variables" | "hiddenFields" | "embeddedFields">;

export const sendVerificationNewEmail = async (
  id: string,
  email: string,
  locale: TUserLocale
): Promise<boolean> => {
  try {
    const t = await getTranslate(locale);
    const token = await createEmailChangeToken(id, email);
    const verifyLink = `${WEBAPP_URL}/verify-email-change?token=${encodeURIComponent(token)}`;

    const html = await renderNewEmailVerification({ verifyLink, t, ...legalProps });

    return await sendEmail({
      emailType: "email_change_verification",
      auditContext: { trigger: "user", actorUserId: id },
      to: email,
      subject: t("emails.verification_new_email_subject"),
      html,
    });
  } catch (error) {
    logger.error(error, "Error in sendVerificationNewEmail");
    throw error;
  }
};

export const sendVerificationEmail = async ({
  id,
  email,
  locale,
  callbackUrl,
  purpose = "email_verification",
  linkTtlSeconds = VERIFICATION_LINK_TTL_SECONDS,
  ssoRecoveryStateId,
}: {
  id: string;
  email: TUserEmail;
  locale: TUserLocale;
  callbackUrl?: string;
  purpose?: TVerificationRequestPurpose;
  /**
   * Overridden only by an SSO-recovery resend, which has to mint a link no longer-lived than the intent
   * it points at — see `getSsoRecoveryPairedTtlSeconds`. Everything else gets the full window.
   */
  linkTtlSeconds?: number;
  /** The SSO recovery the link is for, signed into its token so it cannot be pointed at another (ENG-7310). */
  ssoRecoveryStateId?: string;
}): Promise<boolean> => {
  try {
    const t = await getTranslate(locale);
    const token = createToken(id, {
      expiresIn: linkTtlSeconds,
      purpose,
      ...(ssoRecoveryStateId ? { ssoRecoveryStateId } : {}),
    });
    const { verifyLink, verificationRequestLink } = buildVerificationLinks({
      token,
      webAppUrl: WEBAPP_URL,
      callbackUrl,
      purpose,
      verificationRequestToken: createEmailToken(email),
    });

    const html = await renderVerificationEmail({
      verificationRequestLink,
      verifyLink,
      t,
      ...legalProps,
    });

    return await sendEmail({
      emailType: purpose === "sso_recovery" ? "sso_recovery_verification" : "email_verification",
      auditContext: { trigger: "system" },
      to: email,
      subject: t("emails.verification_email_subject"),
      html,
    });
  } catch (error) {
    logger.error(error, "Error in sendVerificationEmail");
    throw error; // Re-throw the error to maintain the original behavior
  }
};

export const sendPasswordResetLinkEmail = async (user: {
  email: TUserEmail;
  locale: TUserLocale;
  verifyLink: string;
  linkValidityInMinutes: number;
}): Promise<boolean> => {
  const t = await getTranslate(user.locale);
  const html = await renderForgotPasswordEmail({
    verifyLink: user.verifyLink,
    linkValidityInMinutes: user.linkValidityInMinutes,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "password_reset",
    auditContext: { trigger: "system" },
    to: user.email,
    subject: t("emails.forgot_password_email_subject"),
    html,
  });
};

export const sendDeleteAccountConfirmationEmail = async (data: {
  actorUserId?: string;
  email: TUserEmail;
  locale: TUserLocale;
  deleteLink: string;
  linkValidityInMinutes: number;
}): Promise<boolean> => {
  const t = await getTranslate(data.locale);
  const html = await renderAccountDeletionEmail({
    deleteLink: data.deleteLink,
    linkValidityInMinutes: data.linkValidityInMinutes,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "account_deletion",
    auditContext: {
      trigger: data.actorUserId ? "user" : "system",
      actorUserId: data.actorUserId,
    },
    to: data.email,
    subject: t("emails.delete_account_email_subject"),
    html,
  });
};

export const sendVerificationLinkEmail = async (data: {
  email: TUserEmail;
  locale: TUserLocale;
  verifyLink: string;
}): Promise<boolean> => {
  const t = await getTranslate(data.locale);
  const html = await renderVerificationEmail({
    // Better Auth supplies a single verification link; the resend CTA reuses it. Wiring
    // verificationRequestLink to a dedicated Better Auth resend endpoint is a post-cutover
    // refinement tracked in the ENG-1054 runbook, not a blocker for this flow.
    verificationRequestLink: data.verifyLink,
    verifyLink: data.verifyLink,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "email_verification",
    auditContext: { trigger: "system" },
    to: data.email,
    subject: t("emails.verification_email_subject"),
    html,
  });
};

export const sendPasswordResetNotifyEmail = async (user: {
  email: string;
  locale: TUserLocale;
}): Promise<boolean> => {
  const t = await getTranslate(user.locale);
  const html = await renderPasswordResetNotifyEmail({ t, ...legalProps });
  return await sendEmail({
    emailType: "password_reset_notification",
    auditContext: { trigger: "system" },
    to: user.email,
    subject: t("emails.password_reset_notify_email_subject"),
    html,
  });
};

/**
 * Tell a user their account was deleted (ENG-862). Sent after the deletion has committed, so the address
 * comes from the deleted user and nobody can be signed in to receive anything else. Not to be confused with
 * `sendDeleteAccountConfirmationEmail`, the link an SSO user clicks to confirm the deletion.
 */
export const sendAccountDeletedEmail = async (user: {
  email: string;
  locale: TUserLocale;
}): Promise<boolean> => {
  const t = await getTranslate(user.locale);
  const html = await renderAccountDeletedEmail({ t, ...legalProps });
  return await sendEmail({
    emailType: "account_deletion_notification",
    auditContext: { trigger: "system" },
    to: user.email,
    subject: t("emails.account_deleted_email_subject"),
    html,
  });
};

/**
 * Tell a user that SSO recovery removed the local sign-in factors from their account (ENG-2633).
 *
 * Recovery strips the password and any second factor from an account whose address was never proven,
 * because marking it verified would otherwise leave an attacker who registered on someone else's
 * address holding a live credential. No signal separates that attacker from an owner who simply never
 * clicked a verification link, so the strip is unconditional and this mail is what keeps the
 * legitimate case from being a silent downgrade: it names what went and links to re-enrolment.
 */
export const sendSsoRecoveryFactorsRemovedEmail = async ({
  email,
  locale,
  passwordRemoved,
  twoFactorRemoved,
  apiKeysRemoved,
}: {
  email: string;
  locale: TUserLocale;
  passwordRemoved: boolean;
  twoFactorRemoved: boolean;
  /** Keys the account had created were deleted with the strip (ENG-2634). */
  apiKeysRemoved: boolean;
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderSsoRecoveryFactorsRemovedEmail({
    passwordRemoved,
    twoFactorRemoved,
    apiKeysRemoved,
    // The account profile page is where both factors this mail can name are re-enrolled — the password
    // form and the 2FA card both live there. There is no separate /settings/security route.
    securitySettingsLink: `${WEBAPP_URL}/account/settings/profile`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "sso_recovery_notification",
    auditContext: { trigger: "system" },
    to: email,
    subject: t("emails.sso_recovery_factors_removed_email_subject"),
    html,
  });
};

/**
 * Tell a user who asked for a password reset that their account has no password and signs in with an
 * identity provider instead (ENG-3262). Goes only to the address on file, so naming the provider here
 * reveals nothing the forgot-password page does not — that page answers identically for every address.
 */
export const sendSsoSignInHintEmail = async ({
  email,
  locale,
  providerNames,
}: {
  email: string;
  locale: TUserLocale;
  providerNames: string[];
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderSsoSignInHintEmail({
    providerNames,
    loginLink: `${WEBAPP_URL}/auth/login`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "sso_sign_in_hint",
    auditContext: { trigger: "system" },
    to: email,
    subject: t("emails.sso_sign_in_hint_email_subject"),
    html,
  });
};

/**
 * The data retention notice (ENG-3612): what the organisation's policies will act on, for one person.
 * Dates and counts arrive formatted for the reader (their locale, the organisation's time zone). Returns
 * false when SMTP isn't configured; throws when sending fails, so the caller leaves the notice unsent.
 */
export const sendSurveyRetentionNoticeEmail = async ({
  email,
  locale,
  organizationId,
  organizationName,
  archivedSurveys,
  responseDeletions,
}: {
  email: string;
  locale: TUserLocale;
  organizationId: string;
  organizationName: string;
  archivedSurveys: TRetentionNoticeArchivedSurvey[];
  responseDeletions: TRetentionNoticeResponseDeletion[];
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderSurveyRetentionNoticeEmail({
    organizationName,
    archivedSurveys,
    responseDeletions,
    settingsLink: `${WEBAPP_URL}/organizations/${organizationId}/settings/data-retention/exemptions`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "data_retention_notice",
    auditContext: { trigger: "system", organizationId },
    to: email,
    subject: t("emails.retention_notice_email_subject", { organizationName }),
    html,
  });
};

/**
 * An attachment export finished building (ENG-6862). The link opens an app page that checks the reader is
 * the requester, then starts the download, so it outlives any presigned URL. Size and date arrive
 * formatted for the reader. Returns false when SMTP isn't configured; throws when sending fails.
 */
export const sendAttachmentExportReadyEmail = async ({
  email,
  locale,
  userId,
  organizationId,
  surveyId,
  surveyName,
  attachmentExportId,
  archiveSize,
  fileCount,
  includedFileCount,
  sizeLimit,
  retentionMonths,
  expiryDate,
  truncated,
}: {
  email: string;
  locale: TUserLocale;
  userId: string;
  organizationId: string;
  surveyId: string;
  surveyName: string;
  attachmentExportId: string;
  archiveSize: string;
  fileCount: string;
  includedFileCount: string;
  sizeLimit: string;
  retentionMonths: string;
  expiryDate: string;
  truncated: boolean;
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderAttachmentExportReadyEmail({
    surveyName,
    archiveSize,
    fileCount,
    includedFileCount,
    sizeLimit,
    retentionMonths,
    expiryDate,
    truncated,
    downloadLink: `${WEBAPP_URL}/attachment-exports/${attachmentExportId}`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "attachment_export",
    auditContext: { trigger: "user", actorUserId: userId, organizationId, surveyId },
    to: email,
    subject: t("emails.attachment_export_ready_email_subject", { surveyName }),
    html,
  });
};

/**
 * An attachment export could not be built (ENG-6862); the link opens the survey's Responses page to
 * start again. Returns false when SMTP isn't configured; throws when sending fails.
 */
export const sendAttachmentExportFailedEmail = async ({
  email,
  locale,
  userId,
  organizationId,
  workspaceId,
  surveyId,
  surveyName,
  reason,
  maxFiles,
}: {
  email: string;
  locale: TUserLocale;
  userId: string;
  organizationId: string;
  workspaceId: string;
  surveyId: string;
  surveyName: string;
  reason: TAttachmentExportFailureReason;
  maxFiles: string;
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderAttachmentExportFailedEmail({
    surveyName,
    reason,
    maxFiles,
    responsesLink: `${WEBAPP_URL}/workspaces/${workspaceId}/surveys/${surveyId}/responses`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "attachment_export",
    auditContext: { trigger: "user", actorUserId: userId, organizationId, surveyId },
    to: email,
    subject: t("emails.attachment_export_failed_email_subject", { surveyName }),
    html,
  });
};

/**
 * The members policy's notice (ENG-3612), to the member themself, in their locale. Returns false when
 * SMTP isn't configured; throws when sending fails, so the caller leaves the notice unsent.
 */
export const sendMemberRetentionNoticeEmail = async ({
  email,
  locale,
  organizationName,
  deactivateDate,
}: {
  email: string;
  locale: TUserLocale;
  organizationName: string;
  deactivateDate: string;
}): Promise<boolean> => {
  const t = await getTranslate(locale);
  const html = await renderMemberRetentionNoticeEmail({
    organizationName,
    deactivateDate,
    loginLink: `${WEBAPP_URL}/auth/login`,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "data_retention_notice",
    auditContext: { trigger: "system" },
    to: email,
    subject: t("emails.member_retention_notice_email_subject", { organizationName }),
    html,
  });
};

export const sendInviteMemberEmail = async (
  inviteId: string,
  email: string,
  inviterName: string,
  inviteeName: string,
  organizationId: string,
  actorUserId?: string
): Promise<boolean> => {
  const token = createInviteToken(inviteId, email, {
    expiresIn: "7d",
  });
  const t = await getTranslate();

  const verifyLink = `${WEBAPP_URL}/invite?token=${encodeURIComponent(token)}`;

  const html = await renderInviteEmail({
    inviteeName: toEmailDisplayText(inviteeName, ""),
    inviterName: toEmailDisplayText(inviterName, t("common.anonymous")),
    verifyLink,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "invite",
    auditContext: { trigger: actorUserId ? "user" : "system", actorUserId, organizationId, inviteId },
    to: email,
    subject: t("emails.invite_member_email_subject"),
    html,
    rateLimit: { organizationId },
  });
};

export const sendInviteAcceptedEmail = async (
  inviterName: string,
  inviteeName: string,
  email: string,
  inviterLocale?: TUserLocale,
  actorUserId?: string,
  organizationId?: string
): Promise<void> => {
  const t = await getTranslate(inviterLocale);
  // Both names are profile text the invitee or inviter chose, shown in a Formbricks-branded email.
  const html = await renderInviteAcceptedEmail({
    inviteeName: toEmailDisplayText(inviteeName, t("common.anonymous")),
    inviterName: toEmailDisplayText(inviterName, ""),
    t,
    ...legalProps,
  });
  await sendEmail({
    emailType: "invite_accepted",
    auditContext: { trigger: actorUserId ? "user" : "system", actorUserId, organizationId },
    to: email,
    subject: t("emails.invite_accepted_email_subject"),
    html,
  });
};

export const sendResponseFinishedEmail = async (
  email: string,
  locale: TUserLocale,
  workspaceId: string,
  survey: TResponseFinishedEmailSurvey,
  response: TResponse,
  responseCount: number
): Promise<void> => {
  const t = await getTranslate(locale);
  const personEmail = response.contactAttributes?.email;
  const organization = await getOrganizationByWorkspaceId(workspaceId);

  if (!organization) {
    throw new ResourceNotFoundError("Organization", null);
  }

  // Pre-process the element response mapping before passing to email
  const elements = getElementResponseMapping(survey, response);

  // Resolve relative storage URLs to absolute URLs for email rendering
  const elementsWithResolvedUrls = elements.map((element) => {
    if (
      (element.type === TSurveyElementTypeEnum.PictureSelection ||
        element.type === TSurveyElementTypeEnum.FileUpload) &&
      Array.isArray(element.response)
    ) {
      return {
        ...element,
        response: element.response.map((url) => resolveStorageUrl(url)),
      };
    }

    return element;
  });

  // The whitelabel logo is stored as a relative `/storage/...` path, which an email client cannot
  // resolve — it has no origin to resolve against, so the `<img>` renders broken. Resolve it to an
  // absolute URL here, exactly like every other email sender does.
  const logoUrl = organization.whitelabel?.logoUrl
    ? resolveStorageUrl(organization.whitelabel.logoUrl)
    : undefined;

  const html = await renderResponseFinishedEmail({
    survey,
    responseCount,
    response,
    WEBAPP_URL,
    workspaceId,
    organization,
    elements: elementsWithResolvedUrls,
    logoUrl,
    t,
    ...legalProps,
  });

  await sendEmail({
    emailType: "response_notification",
    auditContext: {
      trigger: "response",
      organizationId: organization.id,
      surveyId: survey.id,
      responseId: response.id,
    },
    to: email,
    // Never put the respondent's email address in the subject — it's PII that ends up in
    // notification previews and mailbox lists; replying still reaches them via replyTo.
    subject: t("emails.response_finished_email_subject", {
      surveyName: survey.name,
    }),
    replyTo: personEmail?.toString() ?? MAIL_FROM,
    html,
    rateLimit: { organizationId: organization.id },
  });
};

export const sendEmbedSurveyPreviewEmail = async ({
  to,
  innerHtml,
  workspaceId,
  locale,
  actorUserId,
  logoUrl,
  surveyId,
  organizationId,
}: Readonly<{
  to: string;
  innerHtml: string;
  workspaceId: string;
  locale: TUserLocale;
  actorUserId: string;
  logoUrl?: string;
  surveyId?: string;
  organizationId?: string;
}>): Promise<boolean> => {
  const t = await getTranslate(locale);
  // Resolve relative storage URLs to absolute URLs for email rendering
  const resolvedLogoUrl = logoUrl ? resolveStorageUrl(logoUrl) : undefined;
  const html = await renderEmbedSurveyPreviewEmail({
    html: innerHtml,
    workspaceId,
    logoUrl: resolvedLogoUrl,
    t,
    ...legalProps,
  });
  return await sendEmail({
    emailType: "survey_preview",
    auditContext: { trigger: "user", actorUserId, surveyId, organizationId },
    to,
    subject: t("emails.embed_survey_preview_email_subject"),
    html,
    rateLimit: { actorUserId },
  });
};

export const sendEmailCustomizationPreviewEmail = async (
  to: string,
  userName: string,
  locale: TUserLocale,
  actorUserId: string,
  logoUrl?: string,
  organizationId?: string
): Promise<boolean> => {
  const t = await getTranslate(locale);
  // Resolve relative storage URLs to absolute URLs for email rendering
  const resolvedLogoUrl = logoUrl ? resolveStorageUrl(logoUrl) : undefined;
  const emailHtmlBody = await renderEmailCustomizationPreviewEmail({
    userName,
    logoUrl: resolvedLogoUrl,
    t,
    ...legalProps,
  });

  return await sendEmail({
    emailType: "customization_preview",
    auditContext: { trigger: "user", actorUserId, organizationId },
    to,
    subject: t("emails.email_customization_preview_email_subject"),
    html: emailHtmlBody,
    rateLimit: { actorUserId },
  });
};

// The respondent's request plus what the server reads from the survey and its organization. Never built from
// client input: the action behind the public verify-email screen sets both (ENG-4043).
export type TVerifiedLinkSurveyEmailData = TLinkSurveyEmailData & {
  surveyName: string;
  logoUrl?: string;
};

export const sendLinkSurveyToVerifiedEmail = async (
  data: TVerifiedLinkSurveyEmailData,
  rateLimit: TEmailRateLimitContext
): Promise<boolean> => {
  const surveyId = data.surveyId;
  const email = data.email;
  // Whoever triggers this email picks its recipient, so the survey name is the one piece of the
  // survey owner's free text it carries. Empty when nothing displayable is left; the template then
  // leaves the line out.
  const surveyName = toEmailDisplayText(data.surveyName, "");
  const singleUseId = data.suId;
  const singleUseToken = data.suToken;
  // Resolve relative storage URLs to absolute URLs for email rendering
  const logoUrl = data.logoUrl ? resolveStorageUrl(data.logoUrl) : "";
  const token = createTokenForLinkSurvey(surveyId, email);
  const t = await getTranslate(data.locale);
  const surveyLink = buildVerifiedLinkSurveyUrl({
    publicDomain: getPublicDomain(),
    surveyId,
    token,
    singleUseId,
    singleUseToken,
    surveyLanguageCode: data.surveyLanguageCode,
  });

  const html = await renderLinkSurveyEmail({ surveyName, surveyLink, logoUrl, t, ...legalProps });
  return await sendEmail({
    emailType: "verified_survey_link",
    auditContext: { trigger: "system", surveyId, organizationId: rateLimit.organizationId },
    to: data.email,
    subject: t("emails.verified_link_survey_email_subject"),
    html,
    rateLimit,
  });
};
