import "server-only";
import sanitizeHtml from "sanitize-html";
import { z } from "zod";
import {
  ProcessedHiddenField,
  ProcessedResponseElement,
  ProcessedVariable,
  renderFollowUpEmail,
} from "@formbricks/email";
import { labelEmbeddedFields } from "@formbricks/types/embedded-data-label";
import {
  getComputedEmbeddedFields,
  getIngestedEmbeddedFields,
} from "@formbricks/types/embedded-data-resolver";
import { TResponse } from "@formbricks/types/responses";
import { TSurveyElementTypeEnum } from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { TUserLocale } from "@formbricks/types/user";
import { DEFAULT_LOCALE, IMPRINT_ADDRESS, IMPRINT_URL, PRIVACY_URL, TERMS_URL } from "@/lib/constants";
import { getElementResponseMapping } from "@/lib/responses";
import { buildServerEmbeddedValues } from "@/lib/surveyLogic/utils";
import { parseRecallInfo } from "@/lib/utils/recall";
import { getTranslate } from "@/lingodotdev/server";
import { displayEmbeddedValue } from "@/modules/embedded-data/lib/value-display";
import { resolveStorageUrl } from "@/modules/storage/utils";

/**
 * Sanitize a recall-templated body the same way the survey Follow-Ups email does. Recall tags are
 * expanded against the response first, then only a narrow HTML allowlist survives — so
 * respondent-controlled recall values cannot inject markup or non-http(s) schemes.
 *
 * Recall values are escaped as they are substituted (`escapeValues`). The allowlist below legitimately
 * permits `<a href>` for author-written body HTML, so the sanitizer cannot tell that markup apart from
 * markup a respondent smuggled in through an open-text answer — without escaping, an anonymous
 * respondent could place an arbitrary clickable link into a Formbricks-branded email sent to the
 * survey owner.
 *
 * `ul`/`ol`/`li` are on the list because `sanitize-html` drops a disallowed tag but keeps its text:
 * without them the Body editor's list buttons produced items run together on one line, unnumbered.
 */
const SANITIZE_OPTIONS: sanitizeHtml.IOptions = {
  allowedTags: ["p", "span", "b", "strong", "i", "em", "a", "br", "ul", "ol", "li"],
  allowedAttributes: {
    a: ["href", "rel", "target"],
    // Lexical numbers list items explicitly; keep both so an `<ol>` that starts at something other
    // than 1 keeps its numbering instead of restarting.
    ol: ["start"],
    li: ["value"],
    "*": ["dir", "class"],
  },
  allowedSchemes: ["http", "https"],
  allowedSchemesByTag: {
    a: ["http", "https"],
  },
};

const sanitizeBody = (body: string, survey: TSurvey, response: TResponse, locale?: TUserLocale): string =>
  sanitizeHtml(
    // Pass the resolved locale rather than letting it default to "en-US": recall values include date
    // answers, which parseRecallInfo formats per locale, so defaulting would render US dates in an
    // otherwise correctly localized email.
    parseRecallInfo(
      body,
      // ENG-2538: the survey's readable reserved values merged under the answers, so a body
      // recalling `country` or `durationSeconds` resolves instead of rendering its fallback. The
      // values are escaped as they are substituted, exactly like an answer.
      buildServerEmbeddedValues(response, survey),
      response.variables,
      false,
      locale ?? DEFAULT_LOCALE,
      undefined,
      true
    ),
    SANITIZE_OPTIONS
  );

const buildResponseData = (
  survey: TSurvey,
  response: TResponse,
  attachResponseData: boolean
): ProcessedResponseElement[] => {
  if (!attachResponseData) return [];

  return getElementResponseMapping(survey, response).map((e) => {
    // Resolve relative storage URLs to absolute URLs for picture selection and file upload responses.
    if (
      (e.type === TSurveyElementTypeEnum.PictureSelection || e.type === TSurveyElementTypeEnum.FileUpload) &&
      Array.isArray(e.response)
    ) {
      return {
        element: e.element,
        response: e.response.map((url) => resolveStorageUrl(url)),
        type: e.type,
      };
    }
    return {
      element: e.element,
      response: e.response,
      type: e.type,
    };
  });
};

const buildVariables = (
  survey: TSurvey,
  response: TResponse,
  attachResponseData: boolean,
  includeVariables: boolean
): ProcessedVariable[] => {
  if (!attachResponseData || !includeVariables) return [];

  // ENG-1837: definitions from the EmbeddedData tables; the value read stays the raw response slot,
  // so a response that never captured this field is filtered out rather than shown its default. A
  // true/false field (ENG-6973) reads `true` / `false`, as the exports write it.
  return getComputedEmbeddedFields(survey).flatMap(({ field, link }) => {
    const variableResponse = response.variables[link.storageKey];
    if (variableResponse === undefined) return [];
    return [
      {
        id: link.storageKey,
        name: field.name,
        type: field.dataType === "number" ? ("number" as const) : ("text" as const),
        value: typeof variableResponse === "boolean" ? String(variableResponse) : variableResponse,
      },
    ];
  });
};

const buildHiddenFields = (
  survey: TSurvey,
  response: TResponse,
  attachResponseData: boolean,
  includeHiddenFields: boolean
): ProcessedHiddenField[] => {
  if (!attachResponseData || !includeHiddenFields) return [];

  // ENG-3233: shown by name, read by storage key. `id` stays the storage key — it is the React key
  // in the template, and only the key is unique per survey.
  //
  // ENG-3266: the same widening as the analysis surfaces — a `number` field stores a JSON number,
  // which the old `typeof === "string"` gate dropped, so a follow-up email omitted a row the export
  // wrote. Read once and flat-map rather than filter-then-map: reading the slot twice is what made
  // the `as string` cast necessary, and the cast is what let the two reads drift apart.
  return labelEmbeddedFields(getIngestedEmbeddedFields(survey)).flatMap(({ link, label }) => {
    const value = displayEmbeddedValue(response.data[link.storageKey]);
    if (!value) return [];
    return [{ id: link.storageKey, name: label, value }];
  });
};

/**
 * Builds the branded HTML for a survey-response email (Follow-Ups template): recall-expanded +
 * sanitized body, plus the optional response-data / variables / hidden-fields blocks. Pure of any
 * transport concern — the caller performs the actual send. Shared by survey Follow-Ups and the
 * workflow `send_email` action so both render identically.
 */
export const buildSurveyResponseEmailHtml = async ({
  body,
  survey,
  response,
  attachResponseData,
  includeVariables = false,
  includeHiddenFields = false,
  logoUrl,
  locale,
}: {
  body: string;
  survey: TSurvey;
  response: TResponse;
  attachResponseData: boolean;
  includeVariables?: boolean;
  includeHiddenFields?: boolean;
  logoUrl?: string;
  locale?: TUserLocale;
}): Promise<string> => {
  // Worker context (no request scope) — pass explicit locale to skip headers()/cookies().
  // Falls back to DEFAULT_LOCALE when the respondent locale wasn't captured at submission.
  const t = await getTranslate(locale ?? DEFAULT_LOCALE);

  return renderFollowUpEmail({
    body: sanitizeBody(body, survey, response, locale),
    responseData: buildResponseData(survey, response, attachResponseData),
    variables: buildVariables(survey, response, attachResponseData, includeVariables),
    hiddenFields: buildHiddenFields(survey, response, attachResponseData, includeHiddenFields),
    // 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 (see `@/modules/email`).
    logoUrl: logoUrl ? resolveStorageUrl(logoUrl) : undefined,
    t,
    privacyUrl: PRIVACY_URL || undefined,
    termsUrl: TERMS_URL || undefined,
    imprintUrl: IMPRINT_URL || undefined,
    imprintAddress: IMPRINT_ADDRESS || undefined,
  });
};

/**
 * The same branded email for a workflow run that has no survey response (a Webhook run). The body is
 * sanitized exactly like {@link buildSurveyResponseEmailHtml}; a survey-answer recall token has no
 * response to read, so it renders its fallback, and there are no response-data blocks.
 */
export const buildWorkflowEmailHtml = async ({
  body,
  logoUrl,
  locale,
}: {
  body: string;
  logoUrl?: string;
  locale?: TUserLocale;
}): Promise<string> => {
  const resolvedLocale = locale ?? DEFAULT_LOCALE;
  const t = await getTranslate(resolvedLocale);

  return renderFollowUpEmail({
    body: sanitizeHtml(
      parseRecallInfo(body, {}, {}, false, resolvedLocale, undefined, true),
      SANITIZE_OPTIONS
    ),
    responseData: [],
    variables: [],
    hiddenFields: [],
    logoUrl: logoUrl ? resolveStorageUrl(logoUrl) : undefined,
    t,
    privacyUrl: PRIVACY_URL || undefined,
    termsUrl: TERMS_URL || undefined,
    imprintUrl: IMPRINT_URL || undefined,
    imprintAddress: IMPRINT_ADDRESS || undefined,
  });
};

/** Outcome of resolving a `to` value (literal email or question/hidden-field id) against a response. */
export type ResolveRecipientResult = { ok: true; email: string } | { ok: false; error: string };

/**
 * Resolves an email recipient from a `to` value the same way survey Follow-Ups do:
 *  - if `to` is itself a valid email, use it directly (teammate/user address);
 *  - otherwise treat `to` as a question / hidden-field id and read `response.data[to]`:
 *      - a string is parsed as an email,
 *      - an array (contact-info element) uses index `[2]` as the email,
 *  - anything missing/invalid returns `{ ok: false }` with a clear reason.
 */
export const resolveResponseRecipient = (to: string, response: TResponse): ResolveRecipientResult => {
  const parsedEmailTo = z.email().safeParse(to);
  if (parsedEmailTo.success) {
    return { ok: true, email: parsedEmailTo.data };
  }

  const toValueFromResponse = response.data[to];
  if (!toValueFromResponse) {
    return { ok: false, error: "Recipient value not found in response data" };
  }

  if (typeof toValueFromResponse === "string") {
    const parsedResult = z.email().safeParse(toValueFromResponse);
    if (parsedResult.success) {
      return { ok: true, email: parsedResult.data };
    }
    return { ok: false, error: "Resolved email recipient is not a valid address" };
  }

  if (Array.isArray(toValueFromResponse)) {
    const emailAddress = toValueFromResponse[2];
    if (!emailAddress) {
      return { ok: false, error: "Email address not found in response data" };
    }
    const parsedResult = z.email().safeParse(emailAddress);
    if (parsedResult.success) {
      return { ok: true, email: parsedResult.data };
    }
    return { ok: false, error: "Resolved email recipient is not a valid address" };
  }

  return { ok: false, error: "Resolved email recipient is not a valid address" };
};
