import "server-only";
import type { DeletionCleanupCreateManyInput, Prisma } from "@formbricks/database/prisma";
import { EMAIL_SEND_AUDIT_BUCKET, IS_STORAGE_CONFIGURED } from "@/lib/constants";
import type { TDeletedSurveyResponses } from "@/lib/response/delete-responses";
import { CLEANUP_SETTLE_MS, STORAGE_CLEANUP_CHUNK_SIZE } from "./constants";

export type TSurveyDeletionCleanupInput = {
  organizationId: string;
  workspaceId: string;
  surveyId: string;
  /**
   * Response file URLs outside the survey's upload folder (flat pre-#8044 keys), which the folder delete
   * can't reach. Collected before the delete, since they only exist inside `response.data`.
   */
  fileUrls: readonly string[];
};

/**
 * Queue everything a survey's delete leaves outside the database: its Hub records, its upload folder
 * and any flat-key files. Call it inside the delete's transaction, after locking the survey row: a delete
 * that rolls back then queues nothing, and one that commits always gets its cleanup (ENG-3614).
 *
 * The Hub cleanup covers every feedback directory of the organisation, read here inside the transaction,
 * not just the ones a mapping points at today: a mapping removed earlier still left records behind. The
 * Hub calls stay scoped by `source_type` and `source_id`, so a directory with none of this survey's
 * records costs one empty listing.
 *
 * Returns the ids of the rows to drain straight after commit (the storage ones). The rest wait
 * `CLEANUP_SETTLE_MS` for what can still land after the delete: the Hub cleanup, for records on their way
 * to the Hub, and a second sweep of the upload folder, for an upload signed before the delete.
 *
 * Without file storage (no `S3_BUCKET_NAME`, a supported setup with uploads off) no storage row is
 * queued: nothing can have been uploaded, and a row could never succeed, so it would be retried forever.
 */
export const enqueueSurveyDeletionCleanups = async (
  tx: Prisma.TransactionClient,
  { organizationId, workspaceId, surveyId, fileUrls }: TSurveyDeletionCleanupInput
): Promise<{ drainNowIds: string[] }> => {
  if (EMAIL_SEND_AUDIT_BUCKET) {
    await tx.outboundEmailAudit.updateMany({
      where: { surveyId },
      data: { erasureRequestedAt: new Date() },
    });
  }
  const tenantIds = await readTenantIds(tx, organizationId);
  const scope = { organizationId, workspaceId, surveyId };
  const settledAt = new Date(Date.now() + CLEANUP_SETTLE_MS);

  const drainNow: DeletionCleanupCreateManyInput[] = IS_STORAGE_CONFIGURED
    ? [{ ...scope, kind: "storageSurveyFolder" }, ...storageFileRows(scope, fileUrls)]
    : [];
  const drainLater: DeletionCleanupCreateManyInput[] = IS_STORAGE_CONFIGURED
    ? [{ ...scope, kind: "storageSurveyFolder", nextAttemptAt: settledAt }]
    : [];
  if (tenantIds.length > 0) {
    drainLater.push({ ...scope, kind: "hubSurvey", tenantIds, nextAttemptAt: settledAt });
  }

  return insertCleanups(tx, drainNow, drainLater);
};

export type TResponsesDeletionCleanupInput = {
  organizationId: string;
  workspaceId: string;
  /**
   * The deleted responses, per survey (`deleteResponsesInTransaction`'s `bySurvey`), with their files. At
   * most a batch, so each Hub listing's `submission_id` filter stays short.
   */
  surveys: readonly TDeletedSurveyResponses[];
};

/**
 * Queue what deleting responses leaves outside the database: their files and their Hub records, per
 * survey. Call it inside the delete's transaction, like `enqueueSurveyDeletionCleanups`. The files are
 * drained straight after commit (and, as there, not queued at all without file storage). The Hub records wait `CLEANUP_SETTLE_MS`: a response deleted moments
 * after it was submitted can still have its record on the way to the Hub.
 */
export const enqueueResponsesDeletionCleanups = async (
  tx: Prisma.TransactionClient,
  { organizationId, workspaceId, surveys }: TResponsesDeletionCleanupInput
): Promise<{ drainNowIds: string[] }> => {
  const deleted = surveys.filter((survey) => survey.responseIds.length > 0);
  if (deleted.length === 0) return { drainNowIds: [] };
  if (EMAIL_SEND_AUDIT_BUCKET) {
    await tx.outboundEmailAudit.updateMany({
      where: { responseId: { in: deleted.flatMap((survey) => survey.responseIds) } },
      data: { erasureRequestedAt: new Date() },
    });
  }
  const tenantIds = await readTenantIds(tx, organizationId);
  const settledAt = new Date(Date.now() + CLEANUP_SETTLE_MS);

  const drainNow: DeletionCleanupCreateManyInput[] = [];
  const drainLater: DeletionCleanupCreateManyInput[] = [];
  for (const { surveyId, responseIds, fileUrls } of deleted) {
    const scope = { organizationId, workspaceId, surveyId };
    if (IS_STORAGE_CONFIGURED) drainNow.push(...storageFileRows(scope, fileUrls));
    if (tenantIds.length > 0) {
      drainLater.push({
        ...scope,
        kind: "hubResponses",
        tenantIds,
        responseIds: [...responseIds],
        nextAttemptAt: settledAt,
      });
    }
  }
  return insertCleanups(tx, drainNow, drainLater);
};

export type TResponseFilesDeletionCleanupInput = {
  organizationId: string;
  workspaceId: string;
  surveyId: string;
  /** Files of a response that still exists (a replaced Signature image), as `collectReplacedSignatureFileUrls` picked them. */
  fileUrls: readonly string[];
};

/**
 * Queue the deletion of files a response no longer references while the response itself stays: the old
 * image of a Signature the respondent cleared or redrew. Call it inside the update's transaction, after
 * the write, like the delete variants: an update that rolls back queues nothing, and one that commits
 * always gets its cleanup. No Hub records are queued, as the response is not deleted. The rows wait for
 * the drain job (`DELETION_CLEANUP_DRAIN_INTERVAL_MS`); nothing is shown to anyone in the meantime, so
 * the update does not wait on storage.
 *
 * Without file storage no row is queued, as for the delete variants.
 */
export const enqueueResponseFilesDeletionCleanup = async (
  tx: Prisma.TransactionClient,
  { organizationId, workspaceId, surveyId, fileUrls }: TResponseFilesDeletionCleanupInput
): Promise<void> => {
  if (!IS_STORAGE_CONFIGURED || fileUrls.length === 0) return;

  await insertCleanups(tx, storageFileRows({ organizationId, workspaceId, surveyId }, fileUrls), []);
};

export type TResponseOutcomeCleanupInput = {
  organizationId: string;
  workspaceId: string;
  /** The responses whose outcome just changed, with their survey; the caller passes only real changes. */
  changes: readonly { id: string; surveyId: string }[];
};

/**
 * Queue the Hub cleanup for responses whose outcome changed (ENG-6785): one `hubResponseOutcome` row per
 * response, due at once. The row says only which response to look at; the drain reads its CURRENT outcome and
 * removes or rebuilds the Feedback Records to match, so it is the same row for a mark and for a restore.
 *
 * Call it inside the transaction that writes the outcome: a write that commits always gets its cleanup, and
 * one that rolls back queues nothing. Whatever is still pending for these responses is cancelled first: a
 * restore must not be undone by the older row of the mark before it, and a fresh row reads the same outcome
 * anyway. A row a drain already holds is not waited for: that drain re-reads the outcome after its Hub
 * writes (`reconcileResponseOutcomes`), so it corrects itself.
 *
 * Returns the ids to drain straight after commit. A Hub outage then only delays the cleanup, with the drain's
 * backoff: it never reaches the request that changed the outcome.
 *
 * An organisation with no feedback directory has no Hub tenant, so nothing is queued.
 */
export const enqueueResponseOutcomeCleanups = async (
  tx: Prisma.TransactionClient,
  { organizationId, workspaceId, changes }: TResponseOutcomeCleanupInput
): Promise<{ drainNowIds: string[] }> => {
  if (changes.length === 0) return { drainNowIds: [] };
  const tenantIds = await readTenantIds(tx, organizationId);
  if (tenantIds.length === 0) return { drainNowIds: [] };

  await tx.deletionCleanup.deleteMany({
    where: {
      kind: "hubResponseOutcome",
      workspaceId,
      responseIds: { hasSome: changes.map(({ id }) => id) },
    },
  });
  return insertCleanups(
    tx,
    changes.map(({ id, surveyId }) => ({
      organizationId,
      workspaceId,
      surveyId,
      kind: "hubResponseOutcome" as const,
      tenantIds,
      responseIds: [id],
    })),
    []
  );
};

/** Every feedback directory of the organisation: a Hub tenant that may hold the deleted data's records. */
const readTenantIds = async (tx: Prisma.TransactionClient, organizationId: string): Promise<string[]> =>
  (await tx.feedbackDirectory.findMany({ where: { organizationId }, select: { id: true } })).map(
    (directory) => directory.id
  );

const storageFileRows = (
  scope: Pick<DeletionCleanupCreateManyInput, "organizationId" | "workspaceId" | "surveyId">,
  fileUrls: readonly string[]
): DeletionCleanupCreateManyInput[] => {
  const rows: DeletionCleanupCreateManyInput[] = [];
  for (let i = 0; i < fileUrls.length; i += STORAGE_CLEANUP_CHUNK_SIZE) {
    rows.push({
      ...scope,
      kind: "storageFiles",
      fileKeys: fileUrls.slice(i, i + STORAGE_CLEANUP_CHUNK_SIZE),
    });
  }
  return rows;
};

const insertCleanups = async (
  tx: Prisma.TransactionClient,
  drainNow: DeletionCleanupCreateManyInput[],
  drainLater: DeletionCleanupCreateManyInput[]
): Promise<{ drainNowIds: string[] }> => {
  const created =
    drainNow.length > 0
      ? await tx.deletionCleanup.createManyAndReturn({ data: drainNow, select: { id: true } })
      : [];
  if (drainLater.length > 0) await tx.deletionCleanup.createMany({ data: drainLater });
  return { drainNowIds: created.map((row) => row.id) };
};
