import "server-only";
import { prisma } from "@formbricks/database";
import type { Prisma } from "@formbricks/database/prisma";
import { OperationNotAllowedError } from "@formbricks/types/errors";
import { getEffectiveVisibility } from "./policy";
import { effectivelyRestrictedWhere } from "./predicate";

/**
 * Outbound plumbing (ENG-3283): webhooks, integrations, feedback sources, follow-ups and workflows
 * send a survey's responses to someone outside its access list, so they only ever serve a survey that
 * is workspace-visible *now*. A pending change counts as restricted either way (fail closed).
 *
 * Enforced twice: when a connection is attached (a clear error for the caller) and when a response is
 * dispatched (the attach check cannot see a survey restricted later). Stored visibility facts are
 * enforced even before projection readiness or feature activation.
 */

export const SURVEY_NOT_WORKSPACE_VISIBLE_MESSAGE =
  "Outbound connections can only use surveys that are visible to the whole workspace";

/** The rows an outbound check needs: `getEffectiveVisibility(row) === "restricted"`, as SQL. */
const notWorkspaceVisibleWhere: Prisma.SurveyWhereInput = effectivelyRestrictedWhere;

/** Reads surveys: the app client, or a transaction's so a caller holding a lock needs no second connection. */
type TSurveyReader = Pick<Prisma.TransactionClient, "survey">;

/** Of `surveyIds`, the ones outbound plumbing must not serve. */
export const findNotWorkspaceVisibleSurveyIds = async (
  surveyIds: ReadonlyArray<string>,
  client: TSurveyReader = prisma
): Promise<string[]> => {
  const unique = [...new Set(surveyIds)];
  if (unique.length === 0) return [];

  const rows = await client.survey.findMany({
    where: { id: { in: unique }, ...notWorkspaceVisibleWhere },
    select: { id: true },
  });
  return rows.map(({ id }) => id);
};

/**
 * The same lookup under a name for callers outside outbound plumbing: of `surveyIds`, the effectively
 * restricted ones (`getEffectiveVisibility(row) === "restricted"`), from the stored facts, before
 * projection readiness too.
 */
export const findEffectivelyRestrictedSurveyIds = findNotWorkspaceVisibleSurveyIds;

/**
 * Of `next`, the surveys newly attached and not workspace-visible. Only additions are refused: a survey
 * restricted after it was attached stays on the connection (dispatch skips it), so saving an
 * unrelated edit to that connection must not fail.
 */
export const findNewlyAttachedNotWorkspaceVisibleSurveyIds = (
  next: ReadonlyArray<string>,
  previous: ReadonlyArray<string>,
  client: TSurveyReader = prisma
): Promise<string[]> => {
  const existing = new Set(previous);
  return findNotWorkspaceVisibleSurveyIds(
    next.filter((surveyId) => !existing.has(surveyId)),
    client
  );
};

/** Server-action form of the attach-time guard: the app's generic "not allowed" error, with our copy. */
export const assertNewlyAttachedSurveysWorkspaceVisible = async (
  next: ReadonlyArray<string>,
  previous: ReadonlyArray<string> = [],
  client: TSurveyReader = prisma
): Promise<void> => {
  const blocked = await findNewlyAttachedNotWorkspaceVisibleSurveyIds(next, previous, client);
  if (blocked.length > 0) throw new OperationNotAllowedError(SURVEY_NOT_WORKSPACE_VISIBLE_MESSAGE);
};

type TOutboundVisibilityRow = Parameters<typeof getEffectiveVisibility>[0];

/** Dispatch-time guard over a row already loaded, so the hot path pays no extra query. */
export const isSurveyOutboundAllowed = (row: TOutboundVisibilityRow): boolean =>
  getEffectiveVisibility(row) === "workspace";

/** The columns {@link isSurveyOutboundAllowed} reads, for callers' `select`. */
export const surveyOutboundVisibilitySelect = {
  visibility: true,
  visibilityProjectedVersion: true,
  visibilityVersion: true,
} as const;
