import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { ZSurveyEndings } from "@formbricks/types/surveys/types";
import {
  type WorkflowApiContext,
  type WorkflowAuditDetail,
  createWorkflowsHandlers,
  createWorkflowsService,
} from "@formbricks/workflows/server";
import { getV3AuthorizationActor, getV3SessionUserId, requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { problemWorkflowsNotEntitled } from "@/app/api/v3/lib/response";
import type { TV3AuditLog, TV3Authentication } from "@/app/api/v3/lib/types";
import { ENCRYPTION_KEY, WEBAPP_URL } from "@/lib/constants";
import { resolveSurveyActorContext } from "@/lib/survey/visibility/actor-context";
import { isSurveyOutboundAllowed, surveyOutboundVisibilitySelect } from "@/lib/survey/visibility/outbound";
import { buildHiddenSurveyWhere } from "@/lib/survey/visibility/predicate";
import { normalizeEmailForComparison } from "@/lib/utils/email";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { loggableError } from "@/lib/utils/loggable-error";
import { getWorkspaceMemberEmails } from "@/lib/workspace/service";
import { getIsWorkflowsEnabled } from "@/modules/ee/license-check/lib/utils";
import { workflowSecretStore } from "@/modules/ee/workflows/lib/secret-headers/workflow-secret-store";
import { getWorkflowSurveyLinkSurveys } from "@/modules/ee/workflows/lib/survey-link-surveys";
import { webhookTokenIssuer } from "@/modules/ee/workflows/lib/webhook/token";
import { buildRecordAnalytics } from "./analytics";
import { buildRecordSecretHeaderChanges } from "./secret-audit";
import { type TIsSurveyHidden, loadTestRunResponse } from "./test-run-response";
import { toWorkflowsLogger } from "./workflows-logger";

/**
 * Adapter glue between the Next.js v3 routes and the framework-agnostic `@formbricks/workflows`
 * handlers. The package owns business logic, validation, serialization, and error mapping; this
 * file injects the app's concrete `prisma`/`logger` and binds an `authorize` capability to the
 * authenticated request. The real Prisma client structurally satisfies the package's narrow
 * `WorkflowsDb` port, so no cast is needed; the package never imports `@formbricks/database`.
 */
export const workflowsService = createWorkflowsService({ prisma, webhookTokens: webhookTokenIssuer });

/** Singleton handlers; they are stateless and only close over the injected service. */
export const workflowsHandlers = createWorkflowsHandlers(workflowsService);

/**
 * Confirm a workflow trigger's referenced survey + ending cards exist in the workspace. Injected so
 * `@formbricks/workflows` stays survey-agnostic. Scoped by the survey's `(id, workspaceId)` composite
 * key; ending ids come from the survey's `endings`, parsed through `ZSurveyEndings` so the JSON
 * column is validated (not accessed untyped) before reading ids.
 */
const verifyTriggerSurvey: WorkflowApiContext["verifyTriggerSurvey"] = async ({
  workspaceId,
  surveyId,
  endingCardIds,
}) => {
  const survey = await prisma.survey.findUnique({
    where: { id_workspaceId: { id: surveyId, workspaceId } },
    select: { endings: true, ...surveyOutboundVisibilitySelect },
  });

  if (!survey) {
    return { surveyExists: false, missingEndingCardIds: [] };
  }

  const endingIds = new Set(ZSurveyEndings.parse(survey.endings).map((ending) => ending.id));
  return {
    surveyExists: true,
    // ENG-3283: a workflow forwards the survey's responses, so its survey must be workspace-visible.
    surveyNotWorkspaceVisible: !isSurveyOutboundAllowed(survey),
    missingEndingCardIds: endingCardIds.filter((endingCardId) => !endingIds.has(endingCardId)),
  };
};

/**
 * The surveys in a workspace this caller may not read (ENG-3282), so run history follows its trigger
 * survey. One indexed query over the workspace's restricted surveys — bounded by the per-workspace survey
 * limit — and none at all when nothing is hidden (marker off, an organization administrator).
 */
const buildListUnreadableSurveyIds =
  (authentication: TV3Authentication): WorkflowApiContext["listUnreadableSurveyIds"] =>
  async ({ workspaceId, organizationId, surveyIds }) => {
    const actor = getV3AuthorizationActor(authentication);
    if (!actor) throw new Error("Survey visibility resolved without an authenticated actor");

    const hidden = buildHiddenSurveyWhere(await resolveSurveyActorContext(actor, organizationId));
    if (!hidden || surveyIds?.length === 0) return [];

    const surveys = await prisma.survey.findMany({
      where: { workspaceId, ...(surveyIds ? { id: { in: surveyIds } } : {}), AND: [hidden] },
      select: { id: true },
    });
    return surveys.map((survey) => survey.id);
  };

/**
 * Whether this caller may not read one survey of the workspace (ENG-3282): a Test run against one of
 * its responses, and the list the Test run picker shows, both show its answers.
 */
export const buildIsSurveyHidden =
  (authentication: TV3Authentication): TIsSurveyHidden =>
  async ({ workspaceId, surveyId }) => {
    const organizationId = await getOrganizationIdFromWorkspaceId(workspaceId);
    const hidden = await buildListUnreadableSurveyIds(authentication)({
      workspaceId,
      organizationId,
      surveyIds: [surveyId],
    });
    return hidden.includes(surveyId);
  };

/**
 * Bind the framework-agnostic audit sink to this request's audit log. The handlers call it once,
 * post-mutation, with the affected workflow id + workspace id + before/after snapshots; we copy
 * those onto `auditLog` (target id, old/new object) so the v3 wrapper queues a complete Enterprise
 * event.
 *
 * Organization resolution: the API-key path already set `auditLog.organizationId` from the key's
 * org (see `buildV3AuditLog`); the session path leaves it as `UNKNOWN_DATA`, so we resolve the
 * workflow's real org from `detail.workspaceId` (a first-class field — never inferred from the
 * snapshots, so snapshot reshaping or PII redaction can't silently regress it). Any failure is
 * swallowed and logged — an audit problem must never break or alter an already-successful mutation.
 */
const buildRecordAudit =
  (
    auditLog: TV3AuditLog,
    authentication: TV3Authentication,
    requestId: string
  ): NonNullable<WorkflowApiContext["recordAudit"]> =>
  async (detail: WorkflowAuditDetail) => {
    try {
      auditLog.targetId = detail.targetId;
      auditLog.oldObject = detail.oldObject;
      auditLog.newObject = detail.newObject;

      // API-key auth already carries the org; only the session path needs resolution.
      const isApiKey = !!authentication && "apiKeyId" in authentication;
      if (!isApiKey) {
        auditLog.organizationId = await getOrganizationIdFromWorkspaceId(detail.workspaceId);
      }
    } catch (error) {
      logger.withContext({ requestId }).error(loggableError(error), "Failed to record workflow audit detail");
    }
  };

/**
 * Recipient allowlist for `send_email` actions. Injected so `@formbricks/workflows` stays
 * tenancy-agnostic: given literal recipient emails, returns the subset whose owners cannot access
 * this workspace. Enable/test use it to block a workflow from silently forwarding response data to
 * an arbitrary external inbox (ENG-2029) or to someone whose access to this workspace was revoked
 * (ENG-2186). Scoped to the workspace — not merely to its organization — so it matches both the
 * authoring picker's options and the runner's send-time backstop. Emails are compared
 * case-insensitively.
 */
const verifyRecipientsAllowed: WorkflowApiContext["verifyRecipientsAllowed"] = async ({
  workspaceId,
  emails,
}) => {
  const memberEmails = await getWorkspaceMemberEmails(workspaceId);
  const disallowedEmails = emails.filter((email) => !memberEmails.has(normalizeEmailForComparison(email)));
  return { disallowedEmails };
};

export const buildWorkflowApiContext = (
  authentication: TV3Authentication,
  requestId: string,
  instance: string,
  auditLog?: TV3AuditLog
): WorkflowApiContext => ({
  userId: getV3SessionUserId(authentication),
  requestId,
  instance,
  // Turns the errors the package logs into name and frames (`loggableError`).
  logger: toWorkflowsLogger(logger.withContext({ requestId })),
  // HMAC key for redacting PII markers in audit snapshots; reuses the app's audit/encryption secret
  // so markers aren't offline-guessable. Injected as data to keep `@formbricks/workflows` agnostic.
  auditRedactionKey: ENCRYPTION_KEY,
  // The Webhook Secret URL lives under `/api/v3`, which is served on the app's own URL (with
  // PUBLIC_URL set, `/api/v3` stays admin-domain only), so it is built on WEBAPP_URL.
  webhookBaseUrl: WEBAPP_URL,
  // Workspace access first, then the workflows entitlement (Cloud plan / self-hosted EE license)
  // for the resolved organization. Every v3 route handler and MCP tool authorizes through this
  // capability, so this is the single enforcement point for both surfaces; the returned problem
  // Response short-circuits through the package's error mapping like any authorization failure.
  authorize: async (workspaceId, access) => {
    const authorized = await requireV3WorkspaceAccess(
      authentication,
      workspaceId,
      access,
      requestId,
      instance
    );
    if (authorized instanceof Response) {
      return authorized;
    }
    const isWorkflowsEnabled = await getIsWorkflowsEnabled(authorized.organizationId);
    if (!isWorkflowsEnabled) {
      return problemWorkflowsNotEntitled(requestId, instance);
    }
    return authorized;
  },
  verifyTriggerSurvey,
  verifyRecipientsAllowed,
  listUnreadableSurveyIds: buildListUnreadableSurveyIds(authentication),
  // Secret header values are stored encrypted beside the workflow (ENG-7179, ADR 0043); writes record
  // "secret set / replaced" with the header name only.
  secrets: workflowSecretStore,
  recordSecretHeaderChanges: buildRecordSecretHeaderChanges(authentication, requestId, instance),
  verifySurveyLinkSurveys: getWorkflowSurveyLinkSurveys,
  // Test runs (ENG-7181, ADR 0049): the real runner with fake effects, inside the request. Loaded on use,
  // so the runner and the email renderer stay out of every other workflow route.
  runTest: async (run) =>
    (await import("@/modules/ee/workflows/lib/runner/run-test")).executeWorkflowTestRun(run),
  // A Response completed Test run's response: of the trigger's survey, in this workspace, readable.
  loadTestRunResponse: (input) => loadTestRunResponse(input, buildIsSurveyHidden(authentication)),
  ...(auditLog ? { recordAudit: buildRecordAudit(auditLog, authentication, requestId) } : {}),
  // Product analytics (ENG-2851): always bound, unlike the audit sink, because it no-ops on its own
  // when POSTHOG_KEY is unset and there is no per-request switch to respect.
  recordAnalytics: buildRecordAnalytics(authentication, instance),
});
