import "server-only";
import type { Prisma } from "@formbricks/database/prisma";
import { createEmptyUploadElementIds } from "@/modules/storage/survey-upload-elements";
import { collectResponseFileUrls, getSurveyUploadElementIds } from "@/modules/storage/utils";

// A row whose survey was not read has no element ids, so only keys filed under its own survey and element
// can be collected from it.
const emptyUploadElementIds = createEmptyUploadElementIds();

/** One survey's share of a delete: what the deletion cleanup queue needs per survey. */
export type TDeletedSurveyResponses = {
  surveyId: string;
  /** The ids that matched when the rows were read. */
  responseIds: string[];
  /** The storage files those responses owned, to delete once the transaction commits. */
  fileUrls: string[];
};

export type TDeletedResponses = {
  /** Rows the database actually removed. Authoritative, and may be lower than the rows read. */
  deleted: number;
  /** The ids that matched when the rows were read. */
  deletedIds: string[];
  /** The same rows per survey, with their files; one entry per survey that had any. */
  bySurvey: TDeletedSurveyResponses[];
};

/**
 * Delete the responses matching `where`, and their displays, inside the caller's transaction, returning
 * the files they owned, per survey. The caller queues them for cleanup (`enqueueResponsesDeletionCleanups`)
 * in the same transaction: the URLs only exist inside `response.data`, so they are read here, before
 * the rows are gone.
 *
 * Responses go before displays: `Response_displayId_fkey` is `ON DELETE SET NULL`, so the reverse order
 * would work too, but would first null the column on rows about to be deleted. One survey read per
 * distinct survey, not per response.
 */
export const deleteResponsesInTransaction = async (
  tx: Prisma.TransactionClient,
  where: Prisma.ResponseWhereInput
): Promise<TDeletedResponses> => {
  const rows = await tx.response.findMany({
    where,
    select: { id: true, displayId: true, data: true, surveyId: true },
  });
  if (rows.length === 0) return { deleted: 0, deletedIds: [], bySurvey: [] };

  const surveys = await tx.survey.findMany({
    where: { id: { in: [...new Set(rows.map((row) => row.surveyId))] } },
    select: { id: true, blocks: true, questions: true },
  });
  const uploadElementIds = new Map(
    surveys.map((survey) => [
      survey.id,
      getSurveyUploadElementIds({ blocks: survey.blocks, questions: survey.questions }),
    ])
  );
  const bySurvey = new Map<string, TDeletedSurveyResponses>();
  for (const row of rows) {
    const survey = bySurvey.get(row.surveyId) ?? { surveyId: row.surveyId, responseIds: [], fileUrls: [] };
    survey.responseIds.push(row.id);
    survey.fileUrls.push(
      ...collectResponseFileUrls(
        row.data,
        uploadElementIds.get(row.surveyId) ?? emptyUploadElementIds,
        row.surveyId
      )
    );
    bySurvey.set(row.surveyId, survey);
  }

  // By the ids read, so the rows deleted are exactly the rows whose files were collected.
  const deletedIds = rows.map((row) => row.id);
  const { count } = await tx.response.deleteMany({ where: { AND: [where, { id: { in: deletedIds } }] } });

  const displayIds = rows.map((row) => row.displayId).filter((id): id is string => id !== null);
  if (displayIds.length > 0) {
    await tx.display.deleteMany({ where: { id: { in: displayIds } } });
  }

  return { deleted: count, deletedIds, bySurvey: [...bySurvey.values()] };
};
