import { WEBHOOK_CALLS_PER_MINUTE_PER_WORKFLOW } from "@formbricks/workflows";

/**
 * `failClosed: true` marks the abuse limits: email-sending, account and organization creation, and the
 * brute-force guards. They refuse while Redis is unavailable instead of letting everything through; every
 * other limit fails open so an outage does not take the app down with it
 * (docs/adr/0016-abuse-limits-fail-closed.md).
 */
export const rateLimitConfigs = {
  // Authentication endpoints - stricter limits for security
  auth: {
    login: { interval: 900, allowedPerInterval: 10, namespace: "auth:login" }, // 10 per 15 minutes
    signup: { interval: 3600, allowedPerInterval: 30, namespace: "auth:signup", failClosed: true }, // 30 per hour
    forgotPassword: { interval: 3600, allowedPerInterval: 5, namespace: "auth:forgot", failClosed: true }, // 5 per hour
    // Mail a single account can receive from forgot-password (reset link or SSO hint), keyed by user id, so
    // rotating IPs cannot flood one inbox (ENG-3640). Checked after the response, so hitting it is
    // invisible. Three covers a user who retries a couple of times while the 30-minute link is still live.
    forgotPasswordPerAccount: {
      interval: 3600,
      allowedPerInterval: 3,
      namespace: "auth:forgot:account",
      failClosed: true,
    }, // 3 per hour
    // Keep redemption independent so requesting an email cannot exhaust the budget to use its token.
    resetPassword: {
      interval: 3600,
      allowedPerInterval: 5,
      namespace: "auth:reset-password",
      failClosed: true,
    }, // 5 per hour
    verifyEmail: { interval: 3600, allowedPerInterval: 10, namespace: "auth:verify", failClosed: true }, // 10 per hour
    // Verification email anyone can request for one account, keyed by user id. Below that email's
    // per-recipient cap of 5, so a signed-in resend always has room left (ENG-3823).
    verifyEmailPerAccount: {
      interval: 3600,
      allowedPerInterval: 3,
      namespace: "auth:verify:account",
      failClosed: true,
    }, // 3 per hour
    emailToken: { interval: 3600, allowedPerInterval: 10, namespace: "auth:email-token", failClosed: true }, // 10 per hour — unauthenticated, tells the caller whether an email is registered
    // The SAML callback parses the posted XML before it can tell an IdP from a stranger (ENG-3973), so this caps
    // how often one IP can make it parse. Generous on purpose: every SAML sign-in at a company behind one NAT
    // address lands here, often in a burst at the start of the day. The markup budget is the real bound.
    samlCallback: { interval: 60, allowedPerInterval: 120, namespace: "auth:saml-callback" }, // 120 per minute
  },

  // API endpoints - higher limits for legitimate usage
  api: {
    v1: { interval: 60, allowedPerInterval: 100, namespace: "api:v1" }, // 100 per minute (Management API)
    v2: { interval: 60, allowedPerInterval: 100, namespace: "api:v2" }, // 100 per minute
    v3: { interval: 60, allowedPerInterval: 100, namespace: "api:v3" }, // 100 per minute
    v3StateMutation: {
      interval: 60,
      allowedPerInterval: 120,
      namespace: "api:v3:state-mutation",
    }, // 120 per minute per principal — the API twin of `actions.stateMutation`, for batch writes that fan out to the response pipeline
    mcpAuth: { interval: 60, allowedPerInterval: 30, namespace: "api:mcp:auth", failClosed: true }, // 30 per minute
    // Calls to one workflow's Webhook Secret URL (ENG-7167), keyed by workflow id and counted only once
    // the token matched, so callers without the URL cannot spend it. The default API number, in a
    // namespace of its own. The organization-wide and daily-run quotas are configurable and live in
    // `modules/ee/workflows/lib/webhook/limits.ts`.
    v3WorkflowWebhook: {
      interval: 60,
      allowedPerInterval: WEBHOOK_CALLS_PER_MINUTE_PER_WORKFLOW,
      namespace: "api:v3:workflow-webhook",
    }, // 100 per minute per workflow, the number the trigger panel shows
    // The same number, checked before the database is read and keyed by workflow id plus a prefix of the
    // token's SHA-256 hash (never the token): every wrong token spends its own budget, not the real
    // caller's, while a token repeated past the limit still never reaches the database.
    v3WorkflowWebhookToken: {
      interval: 60,
      allowedPerInterval: WEBHOOK_CALLS_PER_MINUTE_PER_WORKFLOW,
      namespace: "api:v3:workflow-webhook:token",
    }, // 100 per minute per workflow and token
    // "Send test request" on a workflow HTTP request step (ENG-7179): each one is a real outbound call,
    // so a principal gets 30 a minute, REST and MCP together. An outbound-abuse limit: it refuses while
    // Redis is down rather than letting unlimited calls out (ADR 0016).
    v3WorkflowTestRequests: {
      interval: 60,
      allowedPerInterval: 30,
      namespace: "api:v3:workflow-test-request",
      failClosed: true,
    }, // 30 per minute per user or API key
    // A Test run of a workflow's draft (ENG-7181): it sends nothing, but each one saves a run and walks
    // the whole workflow inside the request, so a principal gets 30 a minute, REST and MCP together.
    v3WorkflowTestRuns: {
      interval: 60,
      allowedPerInterval: 30,
      namespace: "api:v3:workflow-test-run",
    }, // 30 per minute per user or API key
    v3SurveyGenerate: {
      interval: 60,
      allowedPerInterval: 10,
      namespace: "api:v3:surveys:generate",
    }, // 10 per minute (AI survey generation)
    v3SurveyVisibility: {
      interval: 60,
      allowedPerInterval: 10,
      namespace: "api:v3:surveys:visibility",
    }, // 10 per minute per actor — a loop of workspace → restricted must not be able to arm the freshness guard (ENG-3282)
    v3SurveysFullList: {
      interval: 60,
      allowedPerInterval: 30,
      namespace: "api:v3:surveys:full-list",
    }, // 30 per minute per principal, on top of v3 — one `view=full` page carries up to 50 whole survey
    // documents, so 30 pages is 1,500 surveys a minute: ample for an export, far below 100 full pages
    v3CustomCss: {
      interval: 60,
      allowedPerInterval: 60,
      namespace: "api:v3:custom-css",
    }, // 60 per minute per principal, on top of v3 — custom CSS processing is synchronous and CPU-bound, and
    // the editor validates ~300 ms after typing stops, so normal editing stays far below this
    v3ChartQueries: {
      interval: 60,
      allowedPerInterval: 600,
      namespace: "api:v3:charts:queries",
    }, // 600 per minute per user or API key, instead of v3 — chart data, preview and field values (ENG-6586).
    // Sized for dashboards: every widget fetches its own data, so a page load is one query per chart.
    v3ChartQueriesInFlight: {
      interval: 120,
      allowedPerInterval: 20,
      namespace: "api:v3:charts:in-flight",
    }, // At most 20 chart queries running at once per user or API key, so one caller cannot fill the shared
    // Cube's queue with 60-second queries. An in-flight limit (`in-flight.ts`), not a window: `interval` is
    // each slot's lease, twice the query timeout, after which a slot a crashed pod never released frees itself.
    // So a slot covers one Cube query: an operation running several (a dashboard filter's value list) takes
    // one per query, never one across them all.
    internalChartGeneration: {
      interval: 60,
      allowedPerInterval: 1,
      namespace: "api:internal:charts:generate",
    }, // 1 per minute per user — bounds concurrent and repeated LLM-backed chart generations
    internalDatasetPurge: {
      interval: 3600,
      allowedPerInterval: 5,
      namespace: "api:internal:feedback-datasets:purge",
    }, // 5 per hour — irreversible and dataset-wide; nobody legitimately purges more often than that
    internalRetentionExport: {
      interval: 3600,
      allowedPerInterval: 10,
      namespace: "api:internal:retention-runs:export",
    }, // 10 per hour — each export streams an organisation's whole retention history (data retention)
    client: { interval: 60, allowedPerInterval: 100, namespace: "api:client" }, // 100 per minute (Client API)
    clientEnvironment: {
      interval: 60,
      allowedPerInterval: 1000,
      namespace: "api:client:environment",
    }, // 1000 per minute per environment (Client API)
    clientCreativeEvents: {
      interval: 60,
      allowedPerInterval: 600,
      namespace: "api:client:creative-events",
    }, // 600 per minute per IP — the SDK sends one creative events request per page view (ENG-4000);
    // an office or carrier NAT puts many visitors behind one IP, and a request over it is dropped
    // silently, so this only bounds a client flooding the counters
  },

  // Server actions - varies by action type
  actions: {
    emailUpdate: { interval: 3600, allowedPerInterval: 3, namespace: "action:email", failClosed: true }, // 3 per hour
    // A signed-in user asking for a reset link to their own address. Its own budget rather than
    // forgot-password's per-account one, which strangers can spend for any address (ENG-3823).
    passwordResetRequest: {
      interval: 3600,
      allowedPerInterval: 3,
      namespace: "action:password-reset-request",
      failClosed: true,
    }, // 3 per hour
    accountDeletion: {
      interval: 3600,
      allowedPerInterval: 5,
      namespace: "action:account-delete",
      failClosed: true,
    }, // 5 per hour
    surveyFollowUp: {
      interval: 3600,
      allowedPerInterval: 50,
      namespace: "action:followup",
      failClosed: true,
    }, // 50 per hour
    sendLinkSurveyEmail: {
      interval: 3600,
      allowedPerInterval: 10,
      namespace: "action:send-link-survey-email",
      failClosed: true,
    }, // 10 per hour
    validateSurveyPin: {
      interval: 60,
      allowedPerInterval: 10,
      namespace: "action:validate-survey-pin",
      failClosed: true,
    }, // 10 per minute — prevents brute-force PIN guessing
    licenseRecheck: { interval: 60, allowedPerInterval: 5, namespace: "action:license-recheck" }, // 5 per minute
    unsplash: { interval: 60, allowedPerInterval: 30, namespace: "action:unsplash" }, // 30 per minute per user — bounds one account exhausting the instance-wide UNSPLASH_ACCESS_KEY quota
    inviteMember: {
      interval: 3600 * 24,
      allowedPerInterval: 50,
      namespace: "action:invite-member",
      failClosed: true,
    }, // 50 recipients per day per org; trusted limits are resolved per organization
    // The same recipient allowance, counted per inviting user across all their organizations. A
    // per-org budget alone is reset by creating another organization, so one account could mail
    // thousands of recipients through throwaway orgs.
    inviteMemberPerUser: {
      interval: 3600 * 24,
      allowedPerInterval: 50,
      namespace: "action:invite-member:user",
      failClosed: true,
    },
    // Per user. Creating an organization is free and each one starts with fresh per-org budgets, so
    // an unbounded create-and-delete loop is a way around every per-org limit.
    createOrganization: {
      interval: 3600 * 24,
      allowedPerInterval: 5,
      namespace: "action:create-organization",
      failClosed: true,
    }, // 5 per day
    generateExampleResponses: {
      interval: 60,
      allowedPerInterval: 1,
      namespace: "action:generate-example-responses",
    }, // 1 per minute per user — closes the multi-click race and bounds LLM spend
    integrationMutation: {
      interval: 60,
      allowedPerInterval: 30,
      namespace: "action:integration-mutation",
    }, // 30 per minute per user — one save or delete per UI interaction, so this bounds a readWrite
    // member churning integration rows (each write hits the provider config and the audit log) without
    // getting in the way of legitimate mapping edits
    feedbackSourceMutation: {
      interval: 60,
      allowedPerInterval: 60,
      namespace: "action:feedback-source-mutation",
    }, // 60 per minute per user
    historicalResponseImport: {
      interval: 3600,
      allowedPerInterval: 10,
      namespace: "action:historical-response-import",
    }, // 10 per hour per user — bounds repeated full-survey imports
    feedbackDirectoryMutation: {
      interval: 60,
      allowedPerInterval: 60,
      namespace: "action:feedback-directory-mutation",
    }, // 60 per minute per user
    feedbackRecordDeletion: {
      interval: 60,
      allowedPerInterval: 100,
      namespace: "action:feedback-record-deletion",
    }, // 100 per minute per user — supports deliberate bulk deletion while bounding abuse
    stateMutation: {
      interval: 60,
      allowedPerInterval: 120,
      namespace: "action:state-mutation",
    }, // 120 per minute per organization/workspace — shared guard for authenticated settings writes
  },

  storage: {
    upload: { interval: 60, allowedPerInterval: 5, namespace: "storage:upload" }, // 5 per minute
    uploadPerWorkspace: {
      interval: 60,
      allowedPerInterval: 100,
      namespace: "storage:upload:workspace",
    }, // 100 per minute per workspace
    delete: { interval: 60, allowedPerInterval: 5, namespace: "storage:delete" }, // 5 per minute
    // One attachment export streams thousands of objects out of S3, so it is bounded far more tightly
    // than a CSV download. Charged inside the route's handler, on the download path only, so the
    // client's dryRun pre-flight does not spend a download's allowance — see the route for why that
    // cannot go through the wrapper's customRateLimitConfig.
    attachmentsExport: {
      interval: 600,
      allowedPerInterval: 3,
      namespace: "storage:attachments-export",
    }, // 3 downloads per 10 minutes
    // The Export modal's download (ENG-6792): a full pass over a survey's responses, in the app's own
    // process. Charged on the download path only; the modal's count requests are not.
    responsesExport: {
      interval: 600,
      allowedPerInterval: 20,
      namespace: "storage:responses-export",
    }, // 20 exports per 10 minutes: enough to try settings, not enough to loop a full pass over a survey
  },
} as const;
