import "server-only";
import { prisma } from "@formbricks/database";
import type { Prisma } from "@formbricks/database/prisma";
import { logger } from "@formbricks/logger";
import type { TI18nString } from "@formbricks/types/i18n";
import type { TResponseFilterCriteria } from "@formbricks/types/responses";
import type { TAccessType } from "@formbricks/types/storage";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { getTextContent } from "@formbricks/types/surveys/validation";
import { getLocalizedValue } from "@/lib/i18n/utils";
import { buildWhereClause } from "@/lib/response/where-clause";
import { replaceHeadlineRecall } from "@/lib/utils/recall";
import { findWorkspaceByIdOrLegacyEnvId } from "@/lib/utils/resolve-client-id";
import { buildAttachmentZipPath } from "@/modules/storage/lib/attachment-zip-paths";
import { type TUploadElementKind, uploadElementKinds } from "@/modules/storage/survey-upload-elements";
import { getOriginalFileNameFromUrl } from "@/modules/storage/url-helpers";
import { getSurveyUploadElementConfigs, parseStorageFileUrl } from "@/modules/storage/utils";
import { getElementsFromBlocks } from "@/modules/survey/lib/client-utils";

/**
 * Collects the file-upload and signature attachments of a survey's responses, ready to be streamed into
 * a ZIP (ENG-1256). Deliberately metadata-only: it never opens a storage stream, so the route can call
 * it first to pre-flight a count and decide whether to start the download at all.
 *
 * ## Why this does not call `getResponses`
 *
 * `getResponses` hydrates tags, contact and quota joins for every response, and
 * `getResponseDownloadFile` shows where that leads — it loops it until the survey is exhausted and holds
 * every fully-hydrated response in memory. An attachment export only needs `id`, `createdAt` and `data`,
 * so it runs its own lean select over the same `buildWhereClause` the CSV export filters with.
 *
 * ## Why every URL's workspace is re-resolved
 *
 * The file URLs come out of `response.data`, i.e. from whoever wrote the response, and the storage key
 * is built from the id in the *URL* rather than from the survey's workspace. Write-time validation
 * (`validateClientFileUploads`) only inspects keys that match a file-upload element existing *at write
 * time*, so a caller can plant a foreign URL under a key that is not yet an element and then edit the
 * survey to turn that key into a file-upload element — a time-of-check/time-of-use gap that makes the
 * planted URL look like a real answer here. `delete-response-files.ts` documents the same gap on the
 * delete side; read its header before changing this. The read side cannot trust the URL's id either, so
 * each one is resolved through `findWorkspaceByIdOrLegacyEnvId` and anything outside the survey's
 * workspace is dropped and reported rather than silently omitted.
 */

export type TAttachmentStatus =
  | "ok"
  | "skipped_foreign_workspace"
  | "skipped_invalid_url"
  // Set by the streaming stage, not the collector: storage confirmed the object is gone.
  | "missing_in_storage"
  // Also from the streaming stage: storage failed for some other reason, so whether the object still
  // exists is unknown. Kept distinct so an outage does not read as data loss.
  | "unavailable_in_storage"
  // The archive hit its byte ceiling before reaching this file. Recorded so the manifest still names
  // every attachment the export was meant to contain.
  | "skipped_export_truncated";

export interface TAttachmentEntry {
  /** Path inside the archive. Unique across the whole export. */
  zipPath: string;
  responseId: string;
  responseCreatedAt: Date;
  elementId: string;
  elementLabel: string;
  originalFileName: string;
  status: TAttachmentStatus;
  /** Filled in by the streaming stage once storage reports the object's size. */
  bytes?: number;
  /** Set only when `status` is `ok` — the coordinates `getFileStreamForDownload` needs. */
  storage?: {
    storageId: string;
    accessType: TAccessType;
    /** Decoded: the object is stored under the decoded name, the URL carries it percent-encoded. */
    fileName: string;
  };
}

export interface CollectResponseAttachmentsParams {
  survey: TSurvey;
  filterCriteria?: TResponseFilterCriteria;
  /**
   * Stop after this many downloadable files. The collector reads one past the limit so the caller can
   * tell "exactly at the cap" from "over the cap" and refuse before any bytes are written.
   */
  maxFiles: number;
  /**
   * IANA zone the response folders' clocks are rendered in — `organization.displayTimeZone`, the same
   * zone the CSV export stamps its Timestamp column with. Defaults to UTC, as that column does.
   */
  timeZone?: string;
  /** Responses fetched per query. */
  batchSize?: number;
}

export interface CollectResponseAttachmentsResult {
  entries: TAttachmentEntry[];
  /** Entries with `status: "ok"` — what the archive will actually contain. */
  fileCount: number;
  /** Responses that contributed at least one attachment. */
  responseCount: number;
  /** True when the survey holds more downloadable files than `maxFiles`. */
  exceedsMaxFiles: boolean;
}

const DEFAULT_BATCH_SIZE = 500;

interface LabelledElement {
  /** 1-based position in the survey, so ZIP folders sort in survey order. */
  index: number;
  label: string;
  /** How this element type stores its answer: one URL string (Signature) or an array of them (File upload). */
  kind: TUploadElementKind;
}

/**
 * Maps each upload element (File upload or Signature) id to its survey position and display label.
 *
 * The label recipe matches `extractSurveyDetails`, so a ZIP folder and its CSV column read the same.
 * A survey holds its elements in `blocks` or in legacy `questions` — never both (`ZSurvey` rejects
 * that) — but `getSurveyUploadElementConfigs` covers both shapes, so this does too. `replaceHeadlineRecall`
 * only rewrites block headlines; a legacy questions-only survey keeps its raw recall tokens in the
 * folder name, which is the same thing the CSV export does.
 */
const buildUploadElementLabels = (survey: TSurvey): Map<string, LabelledElement> => {
  const surveyWithRecall = replaceHeadlineRecall(survey, "default");

  const orderedElements: { id: string; headline?: TI18nString }[] = surveyWithRecall.blocks?.length
    ? getElementsFromBlocks(surveyWithRecall.blocks)
    : (surveyWithRecall.questions ?? []);

  const uploadElementKindsById = new Map(
    getSurveyUploadElementConfigs({
      blocks: surveyWithRecall.blocks,
      questions: surveyWithRecall.questions,
    }).map((config) => [config.id, uploadElementKinds[config.type]])
  );

  const labels = new Map<string, LabelledElement>();

  orderedElements.forEach((element, position) => {
    const kind = uploadElementKindsById.get(element.id);
    if (!kind) return;

    const headline = getTextContent(getLocalizedValue(element.headline, "default"));

    labels.set(element.id, {
      index: position + 1,
      label: headline || element.id,
      kind,
    });
  });

  return labels;
};

/** Cached per distinct storage id: several files in one response normally share one. */
const createWorkspaceResolver = () => {
  const pending = new Map<string, ReturnType<typeof findWorkspaceByIdOrLegacyEnvId>>();

  return (storageId: string) => {
    const cached = pending.get(storageId);
    if (cached) return cached;

    const lookup = findWorkspaceByIdOrLegacyEnvId(storageId);
    pending.set(storageId, lookup);
    return lookup;
  };
};

/**
 * The URLs one answer holds. The element decides the accepted shape, not the value: a Signature answer
 * is one string and a File upload answer an array, so a string under a File upload id (or an array under
 * a Signature id) is malformed data and yields nothing.
 */
const extractFileUrls = (value: unknown, kind: TUploadElementKind): string[] => {
  if (kind.answerShape === "string") {
    // `""` is never a URL, whether or not the element type counts it as a skipped answer.
    return typeof value === "string" && value !== "" ? [value] : [];
  }
  return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === "string") : [];
};

/**
 * The URL carries the percent-encoded name; the object is stored under the decoded one. Returns null
 * on malformed encoding (a bare `%`) instead of throwing: `decodeURIComponent` raises `URIError`, and
 * response data is attacker-supplied, so one bad answer would abort the whole export.
 */
const decodeStoredFileName = (fileName: string): string | null => {
  try {
    return decodeURIComponent(fileName);
  } catch {
    return null;
  }
};

interface AttachmentCandidate {
  elementId: string;
  element: LabelledElement;
  fileUrl: string;
}

/** Flattens a response's file-upload answers into one list, so the collector loops once, not twice. */
const listAttachmentCandidates = (
  data: unknown,
  elementLabels: Map<string, LabelledElement>
): AttachmentCandidate[] => {
  const answers = (data ?? {}) as Record<string, unknown>;

  return [...elementLabels].flatMap(([elementId, element]) =>
    extractFileUrls(answers[elementId], element.kind).map((fileUrl) => ({
      elementId,
      element,
      fileUrl,
    }))
  );
};

type ResolvedStorage =
  | { ok: true; storage: NonNullable<TAttachmentEntry["storage"]> }
  | { ok: false; status: Extract<TAttachmentStatus, `skipped_${string}`> };

/**
 * Turns one answer URL into storage coordinates, or says why it cannot be exported. Every rejection
 * here is a URL the response's author controls, so each is logged and reported rather than thrown.
 */
const resolveAttachmentStorage = async (
  fileUrl: string,
  context: {
    responseId: string;
    elementId: string;
    surveyWorkspaceId: string;
    resolveWorkspace: (storageId: string) => ReturnType<typeof findWorkspaceByIdOrLegacyEnvId>;
  }
): Promise<ResolvedStorage> => {
  const { responseId, elementId, surveyWorkspaceId, resolveWorkspace } = context;

  const storageFile = parseStorageFileUrl(fileUrl);
  if (!storageFile) {
    logger.warn({ responseId, elementId }, "Skipping an attachment with an unparseable storage URL");
    return { ok: false, status: "skipped_invalid_url" };
  }

  const storageWorkspace = await resolveWorkspace(storageFile.storageId);
  if (storageWorkspace?.id !== surveyWorkspaceId) {
    logger.error(
      { responseId, elementId, storageId: storageFile.storageId, surveyWorkspaceId },
      "Refusing to export a response file stored outside the survey's workspace"
    );
    return { ok: false, status: "skipped_foreign_workspace" };
  }

  const fileName = decodeStoredFileName(storageFile.fileName);
  if (fileName === null) {
    logger.warn(
      { responseId, elementId },
      "Skipping an attachment whose storage URL has malformed percent-encoding"
    );
    return { ok: false, status: "skipped_invalid_url" };
  }

  return {
    ok: true,
    storage: { storageId: storageFile.storageId, accessType: storageFile.accessType, fileName },
  };
};

/** Yields matching responses one at a time, fetching them in cursor-paged batches. */
async function* iterateResponses(
  where: Prisma.ResponseWhereInput,
  batchSize: number
): AsyncGenerator<{ id: string; createdAt: Date; data: unknown }> {
  let cursor: string | undefined;

  while (true) {
    const batch = await prisma.response.findMany({
      where,
      select: { id: true, createdAt: true, data: true },
      // Any stable total order works; Prisma's own cursor keeps the batches consistent with it.
      orderBy: [{ createdAt: "desc" }, { id: "desc" }],
      take: batchSize,
      ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
    });

    for (const response of batch) {
      yield response;
    }

    if (batch.length < batchSize) return;
    cursor = batch.at(-1)?.id;
    if (!cursor) return;
  }
}

/** Collects one response's attachments, stopping short if the export has reached `remainingFiles`. */
const collectFromResponse = async (
  response: { id: string; createdAt: Date; data: unknown },
  elementLabels: Map<string, LabelledElement>,
  context: {
    surveyWorkspaceId: string;
    resolveWorkspace: (storageId: string) => ReturnType<typeof findWorkspaceByIdOrLegacyEnvId>;
    usedPaths: Set<string>;
    remainingFiles: number;
    timeZone: string;
  }
): Promise<{ entries: TAttachmentEntry[]; fileCount: number; reachedCap: boolean }> => {
  const entries: TAttachmentEntry[] = [];
  let fileCount = 0;

  for (const { elementId, element, fileUrl } of listAttachmentCandidates(response.data, elementLabels)) {
    const base = {
      responseId: response.id,
      responseCreatedAt: response.createdAt,
      elementId,
      elementLabel: element.label,
      originalFileName: getOriginalFileNameFromUrl(fileUrl),
    };

    const resolved = await resolveAttachmentStorage(fileUrl, {
      responseId: response.id,
      elementId,
      surveyWorkspaceId: context.surveyWorkspaceId,
      resolveWorkspace: context.resolveWorkspace,
    });

    if (!resolved.ok) {
      entries.push({ ...base, zipPath: "", status: resolved.status });
      continue;
    }

    if (fileCount >= context.remainingFiles) {
      return { entries, fileCount, reachedCap: true };
    }

    entries.push({
      ...base,
      zipPath: buildAttachmentZipPath({
        responseId: response.id,
        responseCreatedAt: response.createdAt,
        elementIndex: element.index,
        elementLabel: element.label,
        originalFileName: base.originalFileName,
        timeZone: context.timeZone,
        usedPaths: context.usedPaths,
      }),
      status: "ok",
      storage: resolved.storage,
    });

    fileCount++;
  }

  return { entries, fileCount, reachedCap: false };
};

export const collectResponseAttachments = async ({
  survey,
  filterCriteria,
  maxFiles,
  timeZone = "UTC",
  batchSize = DEFAULT_BATCH_SIZE,
}: CollectResponseAttachmentsParams): Promise<CollectResponseAttachmentsResult> => {
  const elementLabels = buildUploadElementLabels(survey);

  if (elementLabels.size === 0) {
    return { entries: [], fileCount: 0, responseCount: 0, exceedsMaxFiles: false };
  }

  const where: Prisma.ResponseWhereInput = {
    surveyId: survey.id,
    ...buildWhereClause(survey, filterCriteria),
  };

  const context = {
    surveyWorkspaceId: survey.workspaceId,
    resolveWorkspace: createWorkspaceResolver(),
    usedPaths: new Set<string>(),
    remainingFiles: maxFiles,
    timeZone,
  };

  const entries: TAttachmentEntry[] = [];
  let fileCount = 0;
  let responseCount = 0;
  let exceedsMaxFiles = false;

  for await (const response of iterateResponses(where, batchSize)) {
    const collected = await collectFromResponse(response, elementLabels, {
      ...context,
      remainingFiles: maxFiles - fileCount,
    });

    entries.push(...collected.entries);
    fileCount += collected.fileCount;
    if (collected.fileCount > 0) responseCount++;

    if (collected.reachedCap) {
      exceedsMaxFiles = true;
      break;
    }
  }

  return { entries, fileCount, responseCount, exceedsMaxFiles };
};
