import "server-only";
import { after } from "next/server";
import { AsyncLocalStorage } from "node:async_hooks";
import { cache as reactCache } from "react";
import { recordAuthorizationChecksPerRequest } from "./metrics";

/**
 * `page` is the server-rendered route surface (React Server Components), added for ENG-2388.
 *
 * Unlike every other surface, it is not established at a single request boundary: Next.js gives no RSC
 * equivalent of the action-client or API wrapper, and a layout's render and its page's render are
 * separate async contexts. It is therefore opened at the authorization choke points every product
 * route already funnels through, and opening it more than once is idempotent rather than nesting.
 *
 * **`page` is request-scoped; every other surface is callback-scoped.** That difference is ENG-2444.
 * `AsyncLocalStorage` closes when the awaited callback returns, so the surface used to end with the
 * choke-point helper: a page that awaited `getWorkspaceAuth()` and then authorized anything else did
 * so with no surface, and those decisions were labelled `unscoped` in the authoritative decision
 * telemetry the direct-authority rollout is monitored on. Nine routes were affected, two of them
 * issuing one such check *per feedback directory* or *per dashboard widget*.
 *
 * `page` is now held in a React `cache()` slot, which is scoped to the whole render pass, so a layout
 * and its page share one context and it outlives every helper. Two consequences, both improvements on
 * what this comment used to record:
 *
 * A navigation records ONE checks-per-request observation rather than one per choke point, which is
 * the N+1 signal that histogram exists for.
 *
 * `getAuthorizationSurface()` reports `page` for the whole render instead of `unscoped` after the first
 * helper returns, so `formbricks_authzed_authorization_decisions_total` attributes page traffic
 * correctly.
 *
 * Outside a React request scope — scripts, unit tests, any non-RSC caller — `cache()` does not
 * memoize, so there is no slot to hold. `page` then falls back to the `AsyncLocalStorage` boundary,
 * which is the pre-ENG-2444 behaviour: narrower than a render scope, but correct for a caller with no
 * render to scope to.
 */
export type TAuthorizationSurface =
  | "server_action"
  | "page"
  | "api_v1"
  | "api_v2"
  | "api_v3"
  | "mcp"
  | "feedback_gateway";

/**
 * The MCP grant an `mcp` request is held to when it limits organization & workspace access (ENG-7153,
 * ADR-0042): every `can()` for its user also needs `mcp_reach` of the grant on the same node. Absent for
 * All access, API keys and every other surface, which `can()` then decides exactly as before.
 */
export type TAuthorizationMcpGrant = Readonly<{
  id: string;
  userId: string;
}>;

type TAuthorizationContext = {
  checksIssued: number;
  surface: TAuthorizationSurface;
  mcpGrant?: TAuthorizationMcpGrant;
};

type TPageSurfaceSlot = { context: TAuthorizationContext | null };

/**
 * What an MCP tool call learned about its grant's reach (`mcp_reach`): whether a check was denied on it,
 * and whether one confirmed it reaches the resource checked.
 */
export type TMcpReachOutcome = { denied: boolean; confirmed: boolean };

const globalForAuthorization = globalThis as unknown as {
  formbricksAuthorizationContext: AsyncLocalStorage<TAuthorizationContext> | undefined;
  formbricksAuthorizationPageSurfaceSlot: (() => TPageSurfaceSlot) | undefined;
  formbricksMcpReachOutcomes: AsyncLocalStorage<TMcpReachOutcome> | undefined;
};

const authorizationContext =
  globalForAuthorization.formbricksAuthorizationContext ?? new AsyncLocalStorage<TAuthorizationContext>();

globalForAuthorization.formbricksAuthorizationContext = authorizationContext;

const mcpReachOutcomes =
  globalForAuthorization.formbricksMcpReachOutcomes ?? new AsyncLocalStorage<TMcpReachOutcome>();

globalForAuthorization.formbricksMcpReachOutcomes = mcpReachOutcomes;

/**
 * One slot per React request scope. In an RSC render that is the whole render pass, so a layout and
 * its page resolve the same slot — which is what lets the `page` surface outlive the choke-point
 * helper that opened it.
 *
 * `reactCache` is already this codebase's memoization idiom (resolvers.ts, and both choke-point
 * modules); here it is used for its scope rather than to cache a value. The wrapper itself is pinned
 * to `globalThis` so duplicated Next.js server bundles still use the same React cache key.
 */
const getPageSurfaceSlot =
  globalForAuthorization.formbricksAuthorizationPageSurfaceSlot ??
  reactCache((): TPageSurfaceSlot => ({ context: null }));

globalForAuthorization.formbricksAuthorizationPageSurfaceSlot = getPageSurfaceSlot;

/**
 * Whether React is holding a request scope we can hang the `page` surface on.
 *
 * `cache()` only memoizes inside one — outside it (scripts, unit tests, the non-RSC bundle, where the
 * client build's `cache` is a permanent no-op) every call returns a fresh object, so identity is a
 * direct, dependency-free probe. Deliberately not named "is rendering": Next also establishes a scope
 * outside component rendering, and `page` is only ever *selected* by the caller — the ALS store is
 * consulted first, so an enclosing server-action or API surface always keeps precedence.
 */
const hasReactRequestScope = (slot: TPageSurfaceSlot): boolean => slot === getPageSurfaceSlot();

const createSurfaceContext = (
  surface: TAuthorizationSurface,
  mcpGrant?: TAuthorizationMcpGrant
): TAuthorizationContext => ({
  checksIssued: 0,
  surface,
  ...(mcpGrant ? { mcpGrant } : {}),
});

/**
 * Register the one post-response observation for a surface. Shared by both boundaries so they cannot
 * drift, and fail-safe: an unavailable `after()` costs the histogram observation, never the decision.
 *
 * `after()` saves the calling render's store, and Next flips every saved store to phase "after" when the
 * request closes. A render still running then throws on its next fresh `cookies()` / `headers()` call
 * (ENG-3375). On `page` routes, read those request APIs before the surface opens (or through a
 * `cache()`d helper that was called first, like `getSession()`), not later in the render.
 */
const scheduleChecksPerRequestObservation = (context: TAuthorizationContext): void => {
  try {
    after(() => {
      try {
        recordAuthorizationChecksPerRequest(context.checksIssued, context.surface);
      } catch {
        // Telemetry must never alter an authoritative response.
      }
    });
  } catch {
    // A wrapper can be invoked outside a Next.js request in scripts/tests — `after()` is unavailable
    // there. The authorization decision remains authoritative; only the request histogram observation
    // is omitted.
  }
};

/** The surface answering for the current caller: an explicit ALS boundary first, else the page slot. */
const getActiveContext = (): TAuthorizationContext | null =>
  authorizationContext.getStore() ?? getPageSurfaceSlot().context;

export const withAuthorizationSurface = async <T>(
  surface: TAuthorizationSurface,
  callback: () => T | Promise<T>,
  options: Readonly<{ mcpGrant?: TAuthorizationMcpGrant }> = {}
): Promise<T> => {
  if (authorizationContext.getStore()) {
    // A grant narrows; it is never dropped by nesting. Only an outermost `mcp` boundary sets one, so a
    // nested call that names one would be a wiring error: fail closed rather than run without it.
    if (options.mcpGrant && authorizationContext.getStore()?.mcpGrant?.id !== options.mcpGrant.id) {
      throw new Error("An MCP grant must be set on the outermost authorization surface");
    }
    return callback();
  }

  const pageSlot = getPageSurfaceSlot();
  if (hasReactRequestScope(pageSlot) && pageSlot.context) {
    // A request has one outer surface. Before `page` moved from ALS to React cache, a nested wrapper
    // inherited the page context through the early return above. Preserve that behavior so one render
    // cannot split its check count across multiple telemetry observations.
    return callback();
  }

  if (surface === "page") {
    if (hasReactRequestScope(pageSlot)) {
      // Opened once per render, then left open: every later check in the same render — including the
      // ones a page issues long after this helper returned — resolves through this slot.
      if (!pageSlot.context) {
        pageSlot.context = createSurfaceContext(surface);
        scheduleChecksPerRequestObservation(pageSlot.context);
      }
      return callback();
    }
    // No render to scope to: fall through to the async-scoped boundary, which is what this surface did
    // before ENG-2444. Narrower, but correct for a caller with no request scope.
  }

  const context = createSurfaceContext(surface, options.mcpGrant);

  return authorizationContext.run(context, async () => {
    scheduleChecksPerRequestObservation(context);
    return callback();
  });
};

/**
 * Record that one central authorization operation was made. Scalar `can()`/`assertCan()` decisions and
 * narrow list observers each call this exactly once regardless of how much source data they process.
 * A no-op outside a surface — same fail-safe posture as the rest of this module — so scripts and tests
 * that never establish a surface are simply not counted rather than throwing.
 */
export const recordAuthorizationCheckIssued = (): void => {
  const context = getActiveContext();
  if (context) context.checksIssued += 1;
};

/** The number of central authorization operations in the current surface, or `null` outside one. */
export const getIssuedAuthorizationCheckCount = (): number | null => getActiveContext()?.checksIssued ?? null;

/**
 * The MCP grant `actor` is held to in the current request, or `null`. Only the grant's own user is held
 * to it: a check made for anyone else in the same request (a recipient, an invitee) is that person's, and
 * the grant says nothing about it. Read from the `AsyncLocalStorage` boundary only, which is where the
 * `mcp` surface lives; the `page` slot never carries one.
 */
export const getMcpGrantForActor = (
  actor: Readonly<{ type: string; id: string }>
): TAuthorizationMcpGrant | null => {
  const grant = authorizationContext.getStore()?.mcpGrant;
  return grant && actor.type === "user" && actor.id === grant.userId ? grant : null;
};

/** The current bounded request surface, or `unscoped` for scripts and non-request authorization calls. */
export const getAuthorizationSurface = (): TAuthorizationSurface | "unscoped" =>
  getActiveContext()?.surface ?? "unscoped";

/**
 * Runs one MCP tool call and reports what it learned about the grant's reach (ADR-0042): `denied` when a
 * `can()` failed its `mcp_reach` check (or had nothing to check, an id that doesn't exist) or a list
 * lookup dropped an id the user holds; `confirmed` when a `can()` found the grant reaches the resource.
 * The MCP layer turns an error answer into "not found" from these, so an id outside the grant reads like
 * one that doesn't exist, while an answer given about something the grant reaches (a plan refusal, a
 * confirmation, a refusal by the user's own role) reaches the agent unchanged.
 *
 * Per tool call, not per request: a legacy JSON-RPC batch runs several calls in one request, and one
 * call's outcome must not rewrite another's answer. Kept apart from the authorization surface, which
 * counts the whole request's checks.
 */
export const runRecordingMcpReach = async <T>(
  callback: () => Promise<T>
): Promise<{ result: T; reach: TMcpReachOutcome }> => {
  const reach: TMcpReachOutcome = { denied: false, confirmed: false };
  const result = await mcpReachOutcomes.run(reach, callback);
  return { result, reach };
};

/**
 * Runs `callback` without recording what it learns about the grant's reach. For a check that only probes
 * a capability to shape the answer (whether the user administers the organization, say), not one that
 * decides whether the caller may have the resource it asked for: a grant limited to workspaces never
 * reaches the organization node, and that must not turn the call's answer into not found.
 */
export const ignoringMcpReachDenials = <T>(callback: () => Promise<T>): Promise<T> =>
  mcpReachOutcomes.run({ denied: false, confirmed: false }, callback);

/** Records that the current MCP tool call was denied something its grant doesn't reach. No-op outside one. */
export const recordMcpReachDenied = (): void => {
  const reach = mcpReachOutcomes.getStore();
  if (reach) reach.denied = true;
};

/** Records that a check of the current MCP tool call found its grant reaches the resource. */
export const recordMcpReachConfirmed = (): void => {
  const reach = mcpReachOutcomes.getStore();
  if (reach) reach.confirmed = true;
};
