import "server-only";
import { Result, err, ok } from "@formbricks/types/error-handlers";
import { InvalidInputError } from "@formbricks/types/errors";
import { TJsWorkspaceStateSurvey } from "@formbricks/types/js";
import { TSegment } from "@formbricks/types/segment";
import { IMAGE_FILE_EXTENSIONS } from "@formbricks/types/storage";
import { sanitizeThemeStyling } from "@formbricks/types/styling-values";
import { TSurveyBlock } from "@formbricks/types/surveys/blocks";
import {
  TSurveyElement,
  TSurveyElementTypeEnum,
  TSurveyPictureChoice,
} from "@formbricks/types/surveys/elements";
import { TSurvey } from "@formbricks/types/surveys/types";
import { withInlinedEmbeddedFields } from "@/lib/embedded-data/survey-fields";
import { isValidVideoUrl } from "@/lib/utils/video-upload";
import { isValidImageFile } from "@/modules/storage/utils";

/**
 * Actionable hint appended to invalid-image messages. Names the supported formats and explains why
 * extension-less external/CDN URLs (e.g. Unsplash, signed URLs, `?format=auto`) are rejected, since
 * validation keys off the URL's file extension.
 */
const INVALID_IMAGE_HINT = `The URL must end in a supported image extension (${IMAGE_FILE_EXTENSIONS.join(
  ", "
)}). For CDN or extension-less links, upload the image to Formbricks or use a direct image URL.`;

/** The survey row as Prisma returns it, before {@link transformPrismaSurvey} reshapes it. */
type TPrismaSurveyRead = Record<string, unknown> &
  Parameters<typeof withInlinedEmbeddedFields>[0] & {
    segment?: { surveys: { id: string }[] } | null;
    styling?: Parameters<typeof sanitizeThemeStyling>[0] | null;
  };

export const transformPrismaSurvey = <T extends TSurvey | TJsWorkspaceStateSurvey>(
  surveyPrisma: TPrismaSurveyRead
): T => {
  let segment: TSegment | null = null;

  if (surveyPrisma.segment) {
    // The row's segment as Prisma selected it; its relation to surveys is flattened to ids here.
    segment = {
      ...surveyPrisma.segment,
      surveys: surveyPrisma.segment.surveys.map((survey) => survey.id),
    } as TSegment;
  }

  const transformedSurvey = {
    // ENG-1837: swaps the raw `embeddedDataLinks` relation for the inlined `embeddedFields` the read
    // seam consumes, so the Prisma relation shape never leaks onto TSurvey, and derives the legacy
    // `variables` / `hiddenFields` from the same rows (ENG-2404). A no-op for surveys read through a
    // select without the join — those carry no Embedded Data at all.
    ...withInlinedEmbeddedFields(surveyPrisma),
    displayPercentage: Number(surveyPrisma.displayPercentage) || null,
    segment,
    customHeadScriptsMode: surveyPrisma.customHeadScriptsMode,
    // Theme values are not validated on write (the API accepts any string, ENG-3723), so a stored value
    // that could add CSS (ENG-2950) is dropped here, before it reaches the editor, its previews or an API
    // read. The renderer drops the same values, so nothing a respondent sees changes.
    ...(surveyPrisma.styling && { styling: sanitizeThemeStyling(surveyPrisma.styling) }),
  } as T;

  return transformedSurvey;
};

export const anySurveyHasFilters = (surveys: TSurvey[]): boolean => {
  return surveys.some((survey) => {
    if ("segment" in survey && survey.segment) {
      return survey.segment.filters && survey.segment.filters.length > 0;
    }
    return false;
  });
};

export const checkForInvalidImagesInQuestions = (questions: TSurvey["questions"]) => {
  questions.forEach((question, qIndex) => {
    if (question.imageUrl && !isValidImageFile(question.imageUrl)) {
      throw new InvalidInputError(
        `Invalid image file in question ${String(qIndex + 1)}. ${INVALID_IMAGE_HINT}`
      );
    }

    if (question.type === "pictureSelection") {
      if (!Array.isArray(question.choices)) {
        throw new InvalidInputError(`Choices missing for question ${String(qIndex + 1)}`);
      }

      question.choices.forEach((choice, cIndex) => {
        if (!isValidImageFile(choice.imageUrl)) {
          throw new InvalidInputError(
            `Invalid image file for choice ${String(cIndex + 1)} in question ${String(qIndex + 1)}. ${INVALID_IMAGE_HINT}`
          );
        }
      });
    }
  });
};

/**
 * Validates a single choice's image URL
 * @param choice - Choice to validate
 * @param choiceIdx - Index of the choice for error reporting
 * @param elementIdx - Index of the element for error reporting
 * @param blockName - Block name for error reporting
 * @returns Result with void data on success or InvalidInputError on failure
 */
const validateChoiceImage = (
  choice: TSurveyPictureChoice,
  choiceIdx: number,
  elementIdx: number,
  blockName: string
): Result<void, InvalidInputError> => {
  if (choice.imageUrl && !isValidImageFile(choice.imageUrl)) {
    return err(
      new InvalidInputError(
        `Invalid image URL in choice ${choiceIdx + 1} of question ${elementIdx + 1} of block "${blockName}". ${INVALID_IMAGE_HINT}`
      )
    );
  }
  return ok(undefined);
};

/**
 * Validates choice images for picture selection elements
 * Only picture selection elements have imageUrl in choices
 * @param element - Element with choices to validate
 * @param elementIdx - Index of the element for error reporting
 * @param blockName - Block name for error reporting
 * @returns Result with void data on success or InvalidInputError on failure
 */
const validatePictureSelectionChoiceImages = (
  element: TSurveyElement,
  elementIdx: number,
  blockName: string
): Result<void, InvalidInputError> => {
  // Only validate choices for picture selection elements
  if (element.type !== TSurveyElementTypeEnum.PictureSelection) {
    return ok(undefined);
  }

  if (!("choices" in element) || !Array.isArray(element.choices)) {
    return ok(undefined);
  }

  for (let choiceIdx = 0; choiceIdx < element.choices.length; choiceIdx++) {
    const result = validateChoiceImage(element.choices[choiceIdx], choiceIdx, elementIdx, blockName);
    if (!result.ok) {
      return result;
    }
  }

  return ok(undefined);
};

/**
 * Validates a single element's image URL, video URL, and picture selection choice images
 * @param element - Element to validate
 * @param elementIdx - Index of the element for error reporting
 * @param blockIdx - Index of the block for error reporting
 * @param blockName - Block name for error reporting
 * @returns Result with void data on success or InvalidInputError on failure
 */
const validateElement = (
  element: TSurveyElement,
  elementIdx: number,
  blockIdx: number,
  blockName: string
): Result<void, InvalidInputError> => {
  // Check element imageUrl
  if (element.imageUrl && !isValidImageFile(element.imageUrl)) {
    return err(
      new InvalidInputError(
        `Invalid image URL in question ${elementIdx + 1} of block "${blockName}" (block ${blockIdx + 1}). ${INVALID_IMAGE_HINT}`
      )
    );
  }

  // Check element videoUrl
  if (element.videoUrl && !isValidVideoUrl(element.videoUrl)) {
    return err(
      new InvalidInputError(
        `Invalid video URL in question ${elementIdx + 1} of block "${blockName}" (block ${blockIdx + 1}). Only YouTube, Vimeo, and Loom URLs are supported.`
      )
    );
  }

  // Check choices for picture selection
  return validatePictureSelectionChoiceImages(element, elementIdx, blockName);
};

/**
 * Validates that all media URLs (images and videos) in blocks are valid
 * - Validates element imageUrl
 * - Validates element videoUrl
 * - Validates choice imageUrl for picture selection elements
 * @param blocks - Array of survey blocks to validate
 * @returns Result with void data on success or InvalidInputError on failure
 */
export const checkForInvalidMediaInBlocks = (blocks: TSurveyBlock[]): Result<void, InvalidInputError> => {
  for (let blockIdx = 0; blockIdx < blocks.length; blockIdx++) {
    const block = blocks[blockIdx];

    for (let elementIdx = 0; elementIdx < block.elements.length; elementIdx++) {
      const result = validateElement(block.elements[elementIdx], elementIdx, blockIdx, block.name);
      if (!result.ok) {
        return result;
      }
    }
  }

  return ok(undefined);
};

/**
 * Strips isDraft field from elements before saving to database
 * Note: Blocks don't have isDraft since block IDs are CUIDs (not user-editable)
 * Only element IDs need protection as they're user-editable and used in responses
 * @param blocks - Array of survey blocks
 * @returns New array with isDraft stripped from all elements
 */
export const stripIsDraftFromBlocks = (blocks: TSurveyBlock[]): TSurveyBlock[] => {
  return blocks.map((block) => ({
    ...block,
    elements: block.elements.map((element) => {
      const { isDraft: _isDraft, ...elementRest } = element;
      return elementRest;
    }),
  }));
};

/**
 * Validates and prepares blocks for persistence
 * - Validates all media URLs (images and videos) in blocks
 * - Strips isDraft flags from elements
 * @param blocks - Array of survey blocks to validate and prepare
 * @returns Prepared blocks ready for database persistence
 * @throws InvalidInputError if any media validation fails (mapped to a 400 by the API handlers)
 */
export const validateMediaAndPrepareBlocks = (blocks: TSurveyBlock[]): TSurveyBlock[] => {
  // Validate media (images and videos)
  const validation = checkForInvalidMediaInBlocks(blocks);
  if (!validation.ok) {
    // The validation error is an InvalidInputError, so the API layer maps it to a 400 (and never
    // pages Sentry) instead of letting it surface as an unhandled 500.
    throw validation.error;
  }

  // Strip isDraft
  return stripIsDraftFromBlocks(blocks);
};

/**
 * Derives a flat array of elements from the survey's blocks structure
 * Useful for server-side processing where we need to iterate over all questions
 * Note: This is duplicated from the client-side survey utils since this file is server-only
 * @param blocks - Array of survey blocks
 * @returns Flat array of all elements across all blocks. A block stored without `elements` (a draft
 * or migrated block, which nothing validates) contributes none, rather than an `undefined` entry.
 */
export const getElementsFromBlocks = (blocks: TSurveyBlock[]): TSurveyElement[] => {
  return blocks.flatMap((block) => block.elements ?? []);
};

/**
 * Find the location of an element within the survey blocks
 * @param survey - The survey object
 * @param elementId - The ID of the element to find
 * @returns Object containing blockId, blockIndex, elementIndex and the block
 */
export const findElementLocation = (
  survey: TSurvey,
  elementId: string
): { blockId: string | null; blockIndex: number; elementIndex: number; block: TSurveyBlock | null } => {
  const blocks = survey.blocks;

  for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
    const block = blocks[blockIndex];
    const elementIndex = block.elements.findIndex((e) => e.id === elementId);
    if (elementIndex !== -1) {
      return { blockId: block.id, blockIndex, elementIndex, block };
    }
  }

  return { blockId: null, blockIndex: -1, elementIndex: -1, block: null };
};
