import { after } from "next/server";
import { logger } from "@formbricks/logger";
import { AUDIT_LOG_ENABLED, AUDIT_LOG_GET_USER_IP } from "@/lib/constants";
import { ActionClientCtx } from "@/lib/utils/action-client/types/context";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { deepDiff, redactPII } from "@/lib/utils/logger-helpers";
import {
  UNKNOWN_AUDIT_REQUEST_METADATA,
  getAuditRequestMetadata,
} from "@/modules/ee/audit-logs/lib/request-metadata";
import { logAuditEvent } from "@/modules/ee/audit-logs/lib/service";
import {
  TActor,
  TAuditAction,
  TAuditLogEvent,
  TAuditStatus,
  TAuditTarget,
  UNKNOWN_DATA,
} from "@/modules/ee/audit-logs/types/audit-log";
import type { TAuditRequestMetadata } from "@/modules/ee/audit-logs/types/request-metadata";
import { getIsAuditLogsEnabled } from "@/modules/ee/license-check/lib/utils";

export type TAuditEventInput = {
  action: TAuditAction;
  targetType: TAuditTarget;
  userId: string;
  userType: TActor;
  targetId: string;
  organizationId: string;
  status: TAuditStatus;
  oldObject?: Record<string, unknown> | null;
  newObject?: Record<string, unknown> | null;
  eventId?: string;
  apiUrl?: string;
  /** Server-captured metadata for work that outlives its originating request. */
  requestMetadata?: TAuditRequestMetadata;
};

type TBuildAuditEventInput = TAuditEventInput & {
  requestMetadata: TAuditRequestMetadata;
  // When the audited action happened. Taken by the entry point, since the write itself is deferred.
  timestamp: string;
};

/**
 * Builds an audit event and logs it.
 * Redacts sensitive data from the old and new objects before logging.
 * Every exported entry point checks `getIsAuditLogsEnabled` before building or writing an event.
 */
const buildAndLogAuditEvent = async ({
  action,
  targetType,
  userId,
  userType,
  targetId,
  organizationId,
  requestMetadata,
  status,
  oldObject,
  newObject,
  eventId,
  apiUrl,
  timestamp,
}: TBuildAuditEventInput) => {
  try {
    let changes: Record<string, unknown> | undefined;

    if (oldObject && newObject) {
      const diff = deepDiff(oldObject, newObject);
      changes = diff && redactPII(diff);
    } else if (newObject) {
      changes = redactPII(newObject);
    } else if (oldObject) {
      changes = redactPII(oldObject);
    }

    const auditEvent: TAuditLogEvent = {
      actor: { id: userId, type: userType },
      action,
      target: { id: targetId, type: targetType },
      timestamp,
      organizationId,
      status,
      ipAddress: AUDIT_LOG_GET_USER_IP ? requestMetadata.ipAddress : UNKNOWN_DATA,
      userAgent: requestMetadata.userAgent,
      apiUrl,
      ...(changes ? { changes } : {}),
      ...(status === "failure" && eventId ? { eventId } : {}),
    };

    await logAuditEvent(auditEvent);
  } catch (logError) {
    logger.error(logError, "Failed to create audit log event");
  }
};

/** Licence checks and writes remain off the response path for request-bound audit entry points. */
const logRequestAuditEvent = async (input: TAuditEventInput, timestamp: string) => {
  try {
    if (!(await getIsAuditLogsEnabled())) return;
    const requestMetadata = input.requestMetadata ?? (await getAuditRequestMetadata());
    await buildAndLogAuditEvent({ ...input, requestMetadata, timestamp });
  } catch (err) {
    const { action, targetType, targetId, eventId } = input;
    logger.error({ err, action, targetType, targetId, eventId }, "Failed to queue audit event");
  }
};

/** Snapshot metadata while headers are readable, before the unprotected background callback. */
export const queueAuditEventBackground = async (input: TAuditEventInput): Promise<void> => {
  const timestamp = new Date().toISOString();
  const requestMetadata =
    input.requestMetadata ??
    (AUDIT_LOG_ENABLED ? await getAuditRequestMetadata() : UNKNOWN_AUDIT_REQUEST_METADATA);
  setImmediate(() => void logRequestAuditEvent({ ...input, requestMetadata }, timestamp));
};

/**
 * Log after the response without delaying it on a licence lookup. Next.js keeps headers readable in
 * after() for Route Handlers and Server Functions. Outside a request, return a rejection to the caller.
 */
export const queueAuditEvent = (input: TAuditEventInput): Promise<void> => {
  const timestamp = new Date().toISOString();
  return Promise.try(() => after(() => logRequestAuditEvent(input, timestamp)));
};

/** Workers never read request headers. Deferred user work must pass its captured metadata explicitly. */
export const queueAuditEventWithoutRequest = async (input: TAuditEventInput): Promise<void> => {
  const timestamp = new Date().toISOString();
  if (!(await getIsAuditLogsEnabled())) return;
  await buildAndLogAuditEvent({
    ...input,
    requestMetadata: input.requestMetadata ?? UNKNOWN_AUDIT_REQUEST_METADATA,
    timestamp,
  });
};

/**
 * Wraps a handler function with audit logging.
 * Logs audit events for server actions. Specifically for server actions that use next-server-action library middleware and its context.
 * The audit logging runs in the background to avoid blocking the main request.
 *
 * @param action - The type of action to audit.
 * @param targetType - The type of target (e.g., "segment", "survey").
 * @param handler - The handler function to wrap. It can be used with both authenticated and unauthenticated actions.
 **/
export const withAuditLogging = <
  TCtx extends ActionClientCtx = ActionClientCtx,
  TParsedInput = Record<string, unknown>,
  TResult = unknown,
>(
  action: TAuditAction,
  targetType: TAuditTarget,
  handler: (args: { ctx: TCtx; parsedInput: TParsedInput }) => Promise<TResult>
) => {
  return async function wrappedAction(args: { ctx: TCtx; parsedInput: TParsedInput }): Promise<TResult> {
    const { ctx, parsedInput } = args;
    const { auditLoggingCtx } = ctx;
    let result!: TResult;
    let status: TAuditStatus = "success";
    let error: unknown = undefined;

    try {
      result = await handler(args);
    } catch (err) {
      status = "failure";
      error = err;
    }

    // The handler ran fine but reported that the audited thing did not actually happen, so `action`
    // here would be a false record (see AuditLoggingCtx.suppressEvent). Deliberately gated on success:
    // a failure is always audited, so this cannot be used to hide one.
    if (status === "success" && auditLoggingCtx?.suppressEvent) {
      return result;
    }

    // The gate is checked off the request path, so a cold licence lookup never delays the action's
    // response.
    const timestamp = new Date().toISOString();
    setImmediate(async () => {
      try {
        if (!(await getIsAuditLogsEnabled())) return;

        if (!auditLoggingCtx) {
          logger.error("No audit logging context found");
          return;
        }

        const userId: string = ctx?.user?.id ?? UNKNOWN_DATA;
        let organizationId =
          auditLoggingCtx?.organizationId || // NOSONAR // We want to use the organizationId from the auditLoggingCtx if it is present and not empty
          (parsedInput as { organizationId?: string } | undefined)?.organizationId || // NOSONAR // We want to use the organizationId from the parsedInput if it is present and not empty
          UNKNOWN_DATA;

        if (!organizationId) {
          const workspaceId = (parsedInput as { workspaceId?: unknown } | undefined)?.workspaceId;
          if (workspaceId && typeof workspaceId === "string") {
            try {
              organizationId = await getOrganizationIdFromWorkspaceId(workspaceId);
            } catch (err) {
              logger.error(err, "Failed to get organizationId from workspaceId in audit logging");
              organizationId = UNKNOWN_DATA;
            }
          } else {
            organizationId = UNKNOWN_DATA;
          }
        }

        let targetId: string | undefined;
        switch (targetType) {
          case "segment":
            targetId = auditLoggingCtx.segmentId;
            break;
          case "survey":
            targetId = auditLoggingCtx.surveyId;
            break;
          case "organization":
            targetId = auditLoggingCtx.organizationId;
            break;
          case "tag":
            targetId = auditLoggingCtx.tagId;
            break;
          case "webhook":
            targetId = auditLoggingCtx.webhookId;
            break;
          case "user":
            targetId = auditLoggingCtx.userId;
            break;
          case "workspace":
            targetId = auditLoggingCtx.workspaceId;
            break;
          case "language":
            targetId = auditLoggingCtx.languageId;
            break;
          case "invite":
            targetId = auditLoggingCtx.inviteId;
            break;
          case "membership":
            targetId = auditLoggingCtx.membershipId;
            break;
          case "actionClass":
            targetId = auditLoggingCtx.actionClassId;
            break;
          case "contact":
            targetId = auditLoggingCtx.contactId;
            break;
          case "apiKey":
            targetId = auditLoggingCtx.apiKeyId;
            break;
          case "response":
            targetId = auditLoggingCtx.responseId;
            break;
          case "integration":
            targetId = auditLoggingCtx.integrationId;
            break;
          case "quota":
            targetId = auditLoggingCtx.quotaId;
            break;
          case "chart":
            targetId = auditLoggingCtx.chartId;
            break;
          case "dashboard":
            targetId = auditLoggingCtx.dashboardId;
            break;
          case "dashboardWidget":
            targetId = auditLoggingCtx.dashboardWidgetId;
            break;
          case "feedbackDirectory":
            targetId = auditLoggingCtx.feedbackDirectoryId;
            break;
          case "feedbackRecord":
            targetId = auditLoggingCtx.feedbackRecordId;
            break;
          case "feedbackSource":
            targetId = auditLoggingCtx.feedbackSourceId;
            break;
          case "embeddedData":
            targetId = auditLoggingCtx.embeddedDataId;
            break;
          default:
            targetId = UNKNOWN_DATA;
            break;
        }

        targetId ??= UNKNOWN_DATA;

        await buildAndLogAuditEvent({
          action,
          targetType,
          userId,
          userType: "user",
          targetId,
          organizationId,
          requestMetadata: {
            ipAddress: auditLoggingCtx.ipAddress,
            userAgent: auditLoggingCtx.userAgent ?? UNKNOWN_DATA,
          },
          status,
          timestamp,
          oldObject: auditLoggingCtx.oldObject,
          newObject: auditLoggingCtx.newObject,
          eventId: auditLoggingCtx.eventId,
        });
      } catch (logError) {
        logger.error(logError, "Failed to create audit log event");
      }
    });

    if (status === "failure") throw error;
    return result;
  };
};
