import type { CallToolResult } from "@modelcontextprotocol/server";
import { logger } from "@formbricks/logger";
import { buildV3AuditLog, queueV3AuditLog } from "@/app/api/v3/lib/audit";
import { getMcpResourceUrl } from "@/modules/auth/lib/oauth-urls";
import { type TMcpToolContext, getMcpAuthentication, getMcpRequestId, getMcpToolAuthInfo } from "../auth";
import { responseToMcpToolResult } from "../errors";

/**
 * Shared audit lifecycle for every MCP mutation tool, matching what the v3 route wrapper provides:
 * derive the authentication + request id, build the audit log, run the operation, mark
 * success/failure, and ALWAYS queue the audit log (even on throw) before propagating.
 *
 * The per-resource runners (survey/workflow) only supply the audit `resource`, optional logger
 * context, and a `run` callback that performs the actual v3 operation with the injected
 * authentication/requestId/auditLog — so the try/catch/status/queue logic lives in exactly one place.
 */
export async function runMcpMutation(
  ctx: TMcpToolContext,
  {
    action,
    resource,
    logContext = {},
  }: {
    action: Parameters<typeof buildV3AuditLog>[1];
    resource: Parameters<typeof buildV3AuditLog>[2];
    logContext?: Record<string, unknown>;
  },
  run: (args: {
    authentication: ReturnType<typeof getMcpAuthentication>;
    requestId: string;
    auditLog: ReturnType<typeof buildV3AuditLog>;
  }) => Promise<Response>
): Promise<CallToolResult> {
  const authInfo = getMcpToolAuthInfo(ctx);
  const requestId = getMcpRequestId(authInfo);
  const authentication = getMcpAuthentication(authInfo);
  const log = logger.withContext({ requestId, ...logContext });
  // getMcpResourceUrl(), NOT MCP_API_ROUTE: the audit schema validates apiUrl with z.url(), and
  // logAuditEvent catches the failure and downgrades it to a logger.error — so a bare path silently
  // drops the whole event, which is why no MCP mutation was ever audited (ENG-2173). This is the same
  // absolute URL the OAuth protected-resource metadata advertises, so the two agree by construction
  // and it stays correct on a sub-path deployment (WEBAPP_URL=https://host/formbricks).
  const auditLog = buildV3AuditLog(authentication, action, resource, getMcpResourceUrl());

  try {
    const response = await run({ authentication, requestId, auditLog });

    if (auditLog) {
      if (response.ok) {
        auditLog.status = "success";
      } else {
        auditLog.eventId = requestId;
      }
    }

    await queueV3AuditLog(auditLog, requestId, log);
    return await responseToMcpToolResult(response, requestId);
  } catch (error) {
    if (auditLog) {
      auditLog.eventId = requestId;
      await queueV3AuditLog(auditLog, requestId, log);
    }

    throw error;
  }
}
