import { logger } from "@formbricks/logger";
import { TooManyRequestsError } from "@formbricks/types/errors";
import { hashString } from "@/lib/hash-string";
import { UNTRUSTED_CLIENT_IP, getClientIpFromHeaders } from "@/lib/utils/client-ip";
import {
  type TRateLimitReservation,
  checkRateLimit,
  peekRateLimit,
  reserveRateLimit,
  settleRateLimit,
} from "./rate-limit";
import { rateLimitConfigs } from "./rate-limit-configs";
import { type TRateLimitConfig, type TRateLimitResponse } from "./types/rate-limit";

const hashClientIp = (ip: string): string => {
  try {
    return hashString(ip);
  } catch (error) {
    const errorMessage = "Failed to hash IP";
    logger.error({ error }, errorMessage);
    throw new Error(errorMessage);
  }
};

/**
 * Get client identifier for rate limiting with IP hashing
 * Used when the user is not authenticated or the api is called from the client
 *
 * @returns {Promise<string>} Hashed IP address for rate limiting
 * @throws {Error} When IP hashing fails due to invalid IP format or hashing algorithm issues
 */
export const getClientIdentifier = async (): Promise<string> => hashClientIp(await getClientIpFromHeaders());

/**
 * Generic rate limit application function
 *
 * @param config - Rate limit configuration
 * @param identifier - Unique identifier for rate limiting (IP hash, user ID, API key, etc.)
 * @param requested - Number of units to consume atomically; defaults to one
 * @throws {Error} When rate limit is exceeded or rate limiting system fails
 */
const throwIfRateLimitExceeded = <T extends TRateLimitResponse>(result: {
  data?: T;
  error?: string;
  ok: boolean;
}): T => {
  if (!result.ok || !result.data || !result.data.allowed) {
    throw new TooManyRequestsError(
      "Maximum number of requests reached. Please try again later.",
      result.data?.retryAfter
    );
  }

  return result.data;
};

/**
 * Fail fast when the rate limit window is already exhausted.
 * Does not increment the counter.
 */
export const assertRateLimitAvailable = async (
  config: TRateLimitConfig,
  identifier: string
): Promise<TRateLimitResponse> => {
  const result = await peekRateLimit(config, identifier);
  return throwIfRateLimitExceeded(result);
};

export const applyRateLimit = async (
  config: TRateLimitConfig,
  identifier: string,
  requested?: number
): Promise<TRateLimitResponse> => {
  const result =
    requested === undefined
      ? await checkRateLimit(config, identifier)
      : await checkRateLimit(config, identifier, requested);
  return throwIfRateLimitExceeded(result);
};

export const reserveRateLimitUsage = async (
  config: TRateLimitConfig,
  identifier: string,
  requested = 1
): Promise<TRateLimitReservation | undefined> => {
  const result = await reserveRateLimit(config, identifier, requested);
  return throwIfRateLimitExceeded(result).reservation;
};

export const settleRateLimitUsage = async (
  reservation: TRateLimitReservation | undefined,
  successful: number
): Promise<void> => {
  if (!reservation) {
    return;
  }

  await settleRateLimit(reservation, successful);
};

/**
 * Record successful usage against a rate limit without a prior check.
 */
export const recordRateLimitUsage = applyRateLimit;

/**
 * Apply IP-based rate limiting for unauthenticated requests
 * Generic function for IP-based rate limiting in authentication flows and public pages
 *
 * @param config - Rate limit configuration to apply
 * @param options.skipUntrustedClient - Allow, without counting, a request whose client IP Proxy could not
 *   establish. Every such request shares one identity, so counting them would let one caller exhaust the limit
 *   for everyone behind an untrusted forwarding chain; use it where the endpoint has another bound per request.
 * @throws {Error} When rate limit is exceeded or IP hashing fails
 */
export const applyIPRateLimit = async (
  config: TRateLimitConfig,
  options: { skipUntrustedClient?: boolean } = {}
): Promise<TRateLimitResponse> => {
  const ip = await getClientIpFromHeaders();
  if (options.skipUntrustedClient && ip === UNTRUSTED_CLIENT_IP) return { allowed: true };
  return await applyRateLimit(config, hashClientIp(ip));
};

/**
 * Apply public client API rate limiting scoped by environment.
 *
 * The compound environment/IP check keeps the existing per-client behavior without cross-environment
 * interference, while the environment-only check bounds distributed-IP abuse against one environment.
 *
 * @param environmentId - Public client API environment ID from the route params
 * @param customRateLimitConfig - Optional route-specific limit for the environment/IP check
 * @throws {Error} When rate limit is exceeded or IP hashing fails
 */
export const applyClientRateLimit = async (
  environmentId: string,
  customRateLimitConfig?: TRateLimitConfig
): Promise<TRateLimitResponse> => {
  const identifier = await getClientIdentifier();
  const compoundIdentifier = `${environmentId}:${identifier}`;

  await applyRateLimit(customRateLimitConfig ?? rateLimitConfigs.api.client, compoundIdentifier);
  return await applyRateLimit(rateLimitConfigs.api.clientEnvironment, environmentId);
};
