Skip to content

The open alternative to Salesforce, designed for AI.

96.2 KB
Raw Blame
import { Logger } from '@nestjs/common';

import { plainToClass } from 'class-transformer';
import {
  IsDateString,
  IsDefined,
  IsEnum,
  IsIn,
  IsInt,
  IsNotEmpty,
  IsOptional,
  IsString,
  IsUrl,
  Max,
  ValidateIf,
  type ValidationError,
  validateSync,
} from 'class-validator';
import {
  ENTERPRISE_INSTANCE_TYPE,
  type EnterpriseInstanceType,
} from 'twenty-shared/constants';
import { isDefined } from 'twenty-shared/utils';
import { type LoggerOptions } from 'typeorm/logger/LoggerOptions';

import { IsLambdaResourceTags } from 'src/engine/core-modules/logic-function/logic-function-drivers/drivers/lambda/decorators/is-lambda-resource-tags.decorator';
import { LogicFunctionDriverType } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
import { type AwsRegion } from 'src/engine/core-modules/twenty-config/interfaces/aws-region.interface';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
import { SupportDriver } from 'src/engine/core-modules/twenty-config/interfaces/support.interface';

import { IsBillingPlansConfig } from 'src/engine/core-modules/billing/decorators/is-billing-plans-config.decorator';
import { type BillingPlansConfig } from 'src/engine/core-modules/billing/types/billing-plans-config.type';
import { CaptchaDriverType } from 'src/engine/core-modules/captcha/interfaces';
import { CodeInterpreterDriverType } from 'src/engine/core-modules/code-interpreter/code-interpreter.interface';
import { DpaRegion } from 'src/engine/core-modules/dpa/enums/dpa-region.enum';
import { EmailDriver } from 'src/engine/core-modules/email/enums/email-driver.enum';
import { EmailingDomainDriver } from 'src/engine/core-modules/emailing-domain/drivers/types/emailing-domain-driver.type';
import { ExceptionHandlerDriver } from 'src/engine/core-modules/exception-handler/interfaces';
import { StorageDriverType } from 'src/engine/core-modules/file-storage/interfaces';
import { ADDRESS_AUTOCOMPLETE_DRIVER_TYPE } from 'src/engine/core-modules/geo-map/constants/address-autocomplete-driver-type.constant';
import { type AddressAutocompleteDriverType } from 'src/engine/core-modules/geo-map/types/address-autocomplete-driver-type.type';
import {
  LoggerDriverType,
  type TwentyLogLevel,
} from 'src/engine/core-modules/logger/interfaces';
import { type MeterDriver } from 'src/engine/core-modules/metrics/types/meter-driver.type';
import { MeterTemporality } from 'src/engine/core-modules/metrics/types/meter-temporality.type';
import { CastToLogLevelArray } from 'src/engine/core-modules/twenty-config/decorators/cast-to-log-level-array.decorator';
import { CastToMeterDriverArray } from 'src/engine/core-modules/twenty-config/decorators/cast-to-meter-driver.decorator';
import { CastToPositiveNumber } from 'src/engine/core-modules/twenty-config/decorators/cast-to-positive-number.decorator';
import { CastToTypeORMLogLevelArray } from 'src/engine/core-modules/twenty-config/decorators/cast-to-typeorm-log-level-array.decorator';
import { CastToUpperSnakeCase } from 'src/engine/core-modules/twenty-config/decorators/cast-to-upper-snake-case.decorator';
import { ConfigVariablesMetadata } from 'src/engine/core-modules/twenty-config/decorators/config-variables-metadata.decorator';
import { IsAWSRegion } from 'src/engine/core-modules/twenty-config/decorators/is-aws-region.decorator';
import { DEFAULT_WORKSPACE_AUTO_LOGIN_WINDOW } from 'src/engine/core-modules/auth/constants/default-workspace-auto-login-window.constant';
import { IsNonNegativeDuration } from 'src/engine/core-modules/twenty-config/decorators/is-non-negative-duration.decorator';
import { IsPositiveDuration } from 'src/engine/core-modules/twenty-config/decorators/is-positive-duration.decorator';
import { IsOptionalOrEmptyString } from 'src/engine/core-modules/twenty-config/decorators/is-optional-or-empty-string.decorator';
import { IsStrictlyLowerThan } from 'src/engine/core-modules/twenty-config/decorators/is-strictly-lower-than.decorator';
import { IsTwentySemVer } from 'src/engine/core-modules/twenty-config/decorators/is-twenty-semver.decorator';
import { ConfigVariableType } from 'src/engine/core-modules/twenty-config/enums/config-variable-type.enum';
import { ConfigVariablesGroup } from 'src/engine/core-modules/twenty-config/enums/config-variables-group.enum';
import {
  ConfigVariableException,
  ConfigVariableExceptionCode,
} from 'src/engine/core-modules/twenty-config/twenty-config.exception';
import { type OnboardingEnrichmentCreditRewardTier } from 'src/engine/core-modules/onboarding/types/onboarding-enrichment-credit-reward-tier.type';
import { type PlanUsageLimitDefaults } from 'src/engine/core-modules/usage-limit/types/plan-usage-limit-defaults.type';
import { type AiProvidersConfig } from 'src/engine/metadata-modules/ai/ai-models/types/ai-providers-config.type';
import {
  DEFAULT_DISABLED_MODELS,
  DEFAULT_MODELS_BY_TIER,
} from 'src/engine/metadata-modules/ai/ai-models/utils/load-default-model-preferences.util';

export class ConfigVariables {
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Enable or disable password authentication for users',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  AUTH_PASSWORD_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Prefills [email protected] in the login form, used in local development for quicker sign-in',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  @ValidateIf((env) => env.AUTH_PASSWORD_ENABLED)
  SIGN_IN_PREFILLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Require email verification for user accounts',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_EMAIL_VERIFICATION_REQUIRED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Hostnames or IP literals on a private network that outbound connections may reach, e.g. an on-premise mail server or identity provider (keycloak, mail.internal, 192.168.1.10). Exact hostname match, no patterns; a full URL is reduced to its hostname. Every other private address is blocked (SSRF protection) for HTTP workflow actions, webhooks, SSO and IMAP/SMTP/CalDAV connections. Set to * to allow all.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS: string[] = [];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Accept IMAP and SMTP servers whose TLS certificate cannot be verified, e.g. self-signed. Prefer adding your CA with NODE_EXTRA_CA_CERTS, which keeps verification on.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IMAP_SMTP_ALLOW_SELF_SIGNED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Deprecated: set OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS to * instead. While this is false every private address is reachable and OUTBOUND_HTTP_ALLOWED_INTERNAL_HOSTS is ignored.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  OUTBOUND_HTTP_SAFE_MODE_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Lock workspace schema DDL changes (for hot upgrades). Blocks sign-up, workspace deletion, and all metadata schema changes.',
    isEnvOnly: true,
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  WORKSPACE_SCHEMA_DDL_LOCKED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the email verification token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  EMAIL_VERIFICATION_TOKEN_EXPIRES_IN = '1h';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the password reset token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  PASSWORD_RESET_TOKEN_EXPIRES_IN = '5m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Duration for which an admin-issued two-factor authentication recovery code is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_EXPIRES_IN = '1h';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    description: 'Enable or disable the Google Calendar integration',
    type: ConfigVariableType.BOOLEAN,
  })
  CALENDAR_PROVIDER_GOOGLE_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    description: 'Callback URL for Google Auth APIs',
    type: ConfigVariableType.STRING,
    isSensitive: false,
  })
  AUTH_GOOGLE_APIS_CALLBACK_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    description: 'Enable or disable Google Single Sign-On (SSO)',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  AUTH_GOOGLE_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    isSensitive: false,
    description: 'Client ID for Google authentication',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.AUTH_GOOGLE_ENABLED)
  AUTH_GOOGLE_CLIENT_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    isSensitive: true,
    description: 'Client secret for Google authentication',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.AUTH_GOOGLE_ENABLED)
  AUTH_GOOGLE_CLIENT_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    isSensitive: false,
    description: 'Callback URL for Google authentication',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @ValidateIf((env) => env.AUTH_GOOGLE_ENABLED)
  AUTH_GOOGLE_CALLBACK_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    description: 'Enable or disable the Gmail messaging integration',
    type: ConfigVariableType.BOOLEAN,
  })
  MESSAGING_PROVIDER_GMAIL_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    isSensitive: false,
    description:
      'Google Cloud Pub/Sub topic that Gmail push notifications publish to ' +
      '(format: projects/<project>/topics/<topic>). Required for webhook-based Gmail sync.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  MESSAGING_GMAIL_PUBSUB_TOPIC: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.GOOGLE_AUTH,
    isSensitive: false,
    description:
      'Service account email authorized to deliver Gmail Pub/Sub push ' +
      'notifications. The signed OIDC token on each push is verified against ' +
      'this email. Required for webhook-based Gmail sync.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  MESSAGING_GMAIL_PUBSUB_VERIFICATION_EMAIL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Enable webhook-based sync for connected accounts (provider push ' +
      'notifications on top of polling). Requires publicly reachable ' +
      'webhook endpoints.',
    type: ConfigVariableType.BOOLEAN,
  })
  IS_CONNECTED_ACCOUNT_WEBHOOK_SUBSCRIPTION_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Enable or disable the IMAP messaging integration',
    type: ConfigVariableType.BOOLEAN,
  })
  IS_IMAP_SMTP_CALDAV_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Enable or disable the connection test when saving IMAP/SMTP/CALDAV accounts',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_IMAP_SMTP_CALDAV_CONNECTION_TEST_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      "Enable or disable requests to twenty-icons to get companies' icons",
    type: ConfigVariableType.BOOLEAN,
  })
  ALLOW_REQUESTS_TO_TWENTY_ICONS = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    description: 'Enable or disable Microsoft authentication',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  AUTH_MICROSOFT_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    isSensitive: false,
    description: 'Client ID for Microsoft authentication',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.AUTH_MICROSOFT_ENABLED)
  AUTH_MICROSOFT_CLIENT_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    isSensitive: true,
    description: 'Client secret for Microsoft authentication',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.AUTH_MICROSOFT_ENABLED)
  AUTH_MICROSOFT_CLIENT_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    isSensitive: false,
    description: 'Callback URL for Microsoft authentication',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @ValidateIf((env) => env.AUTH_MICROSOFT_ENABLED)
  AUTH_MICROSOFT_CALLBACK_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    isSensitive: false,
    description: 'Callback URL for Microsoft APIs',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @ValidateIf((env) => env.AUTH_MICROSOFT_ENABLED)
  AUTH_MICROSOFT_APIS_CALLBACK_URL: string;

  /**
   * @deprecated Use is now GA - record page layouts are always seeded
   */
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Deprecated - record page layouts are now always seeded (GA)',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  SHOULD_SEED_STANDARD_RECORD_PAGE_LAYOUTS = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    description: 'Enable or disable the Microsoft messaging integration',
    type: ConfigVariableType.BOOLEAN,
  })
  MESSAGING_PROVIDER_MICROSOFT_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Number of messages fetched per batch during message import, adjust incase of rate limiting caused by Gmail, Outlook or IMAP',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  MESSAGING_MESSAGES_GET_BATCH_SIZE = 400;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.MICROSOFT_AUTH,
    description: 'Enable or disable the Microsoft Calendar integration',
    type: ConfigVariableType.BOOLEAN,
  })
  CALENDAR_PROVIDER_MICROSOFT_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the access token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  ACCESS_TOKEN_EXPIRES_IN = '30m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the workspace agnostic token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  WORKSPACE_AGNOSTIC_TOKEN_EXPIRES_IN = '30m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the refresh token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  REFRESH_TOKEN_EXPIRES_IN = '60d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Grace period allowing concurrent refresh token use (e.g. two tabs refreshing simultaneously). Reuse after this window triggers suspicious activity detection.',
    type: ConfigVariableType.STRING,
  })
  @IsNonNegativeDuration()
  @IsOptional()
  REFRESH_TOKEN_REUSE_GRACE_PERIOD = '1m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Absolute lifetime of a cookie-based user session, set at sign-in and never extended',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  SESSION_ABSOLUTE_LIFETIME = '180d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Duration of inactivity after which a cookie-based user session expires',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  SESSION_IDLE_TIMEOUT = '30d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Window after authenticating on the workspace-agnostic domain during which a user-level session can still auto-login into a workspace without re-authenticating',
    type: ConfigVariableType.STRING,
  })
  @IsNonNegativeDuration()
  @IsOptional()
  WORKSPACE_AUTO_LOGIN_WINDOW: string = DEFAULT_WORKSPACE_AUTO_LOGIN_WINDOW;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'SameSite attribute of the user session cookie. Use none only for split-origin deployments, behind https',
    type: ConfigVariableType.STRING,
  })
  @IsIn(['lax', 'strict', 'none'])
  @IsOptional()
  AUTH_COOKIE_SAME_SITE: 'lax' | 'strict' | 'none' = 'lax';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Comma-separated list of extra origins allowed to send credentialed cross-origin requests (split-origin deployments)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  AUTH_COOKIE_ALLOWED_ORIGINS = '';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the login token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  LOGIN_TOKEN_EXPIRES_IN = '15m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the file token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  FILE_TOKEN_EXPIRES_IN = '1d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the invitation token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  INVITATION_TOKEN_EXPIRES_IN = '30d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which the short-term token is valid',
    type: ConfigVariableType.STRING,
  })
  SHORT_TERM_TOKEN_EXPIRES_IN = '5m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which an application access token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  APPLICATION_ACCESS_TOKEN_EXPIRES_IN = '30m';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Duration for which an application refresh token is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  APPLICATION_REFRESH_TOKEN_EXPIRES_IN = '60d';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description:
      'Duration for which a playground token (in-app REST/GraphQL playground bearer) is valid',
    type: ConfigVariableType.STRING,
  })
  @IsPositiveDuration()
  @IsOptional()
  PLAYGROUND_TOKEN_EXPIRES_IN = '2h';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'Email address used as the sender for outgoing emails',
    type: ConfigVariableType.STRING,
  })
  EMAIL_FROM_ADDRESS = '[email protected]';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'Name used in the From header for outgoing emails',
    type: ConfigVariableType.STRING,
  })
  EMAIL_FROM_NAME = 'Felix from Twenty';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'Email driver to use for sending emails',
    type: ConfigVariableType.ENUM,
    options: Object.values(EmailDriver),
  })
  @CastToUpperSnakeCase()
  EMAIL_DRIVER: EmailDriver = EmailDriver.LOGGER;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'SMTP host for sending emails',
    type: ConfigVariableType.STRING,
  })
  EMAIL_SMTP_HOST: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'Use unsecure connection for SMTP',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  EMAIL_SMTP_NO_TLS = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description:
      'Hostname sent in the SMTP EHLO greeting. Defaults to the machine hostname; set a fully qualified name if the relay rejects it',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  EMAIL_SMTP_NAME: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'SMTP port for sending emails',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SMTP_PORT = 587;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    description: 'SMTP user for authentication',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  EMAIL_SMTP_USER: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.EMAIL_SETTINGS,
    isSensitive: true,
    description: 'SMTP password for authentication',
    type: ConfigVariableType.STRING,
  })
  EMAIL_SMTP_PASSWORD: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'When enabled, only server admins can create new workspaces, and signing up without a pending invitation or an approved access domain is refused. Ignored during initial setup when no workspace exists.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_WORKSPACE_CREATION_LIMITED_TO_SERVER_ADMINS = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'When enabled, server admins can toggle any feature flag for any workspace from the admin panel. Always enabled in development mode and when billing is enabled.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_FEATURE_FLAG_MANAGEMENT_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Deployment region that determines the DPA hosting location shown to customers. The Processor entity (Twenty.com PBC) and governing law (Delaware, USA) are the same for all regions. EU (default) = Frankfurt, Germany; US = United States. Must match where Customer Personal Data actually lives.',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.ENUM,
    options: Object.values(DpaRegion),
    // Env-only: a runtime override could advertise a hosting location that does not match where data lives.
    isEnvOnly: true,
  })
  @IsOptional()
  @IsEnum(DpaRegion)
  DPA_DEPLOYMENT_REGION: DpaRegion = DpaRegion.EU;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description: 'Type of storage to use (local or S3)',
    type: ConfigVariableType.ENUM,
    options: Object.values(StorageDriverType),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  STORAGE_TYPE: StorageDriverType = StorageDriverType.LOCAL;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description: 'Local path for storage when using local storage type',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.LOCAL)
  STORAGE_LOCAL_PATH = '.local-storage';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Region of the S3 bucket (e.g. "eu-west-3" for AWS, or a provider-specific slug like "fr-par" for Scaleway). Required.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsString()
  @IsNotEmpty()
  STORAGE_S3_REGION: AwsRegion;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description: 'Name of the S3 bucket used for file storage. Required.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  STORAGE_S3_NAME: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Custom S3 endpoint URL. Optional — only needed for S3-compatible services like MinIO (e.g. http://minio:9000). Omit for native AWS S3, where the SDK resolves the endpoint from the region automatically.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsOptional()
  STORAGE_S3_ENDPOINT: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    isSensitive: true,
    description:
      'S3 access key ID. Optional — omit to use the default AWS credential chain (IAM role, instance profile, etc.).',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsOptional()
  STORAGE_S3_ACCESS_KEY_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    isSensitive: true,
    description:
      'S3 secret access key. Required when STORAGE_S3_ACCESS_KEY_ID is set, ignored otherwise.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsOptional()
  STORAGE_S3_SECRET_ACCESS_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'When enabled, file downloads are 302-redirected to S3 presigned URLs and direct uploads go straight to S3 via presigned PUT URLs instead of being proxied through the server. Reduces server load and bandwidth. Requires a bucket CORS policy allowing PUT from the frontend origin.',
    type: ConfigVariableType.BOOLEAN,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsOptional()
  // TODO: default to true once validated in production
  STORAGE_S3_PRESIGNED_URL_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Public S3 endpoint used for generating presigned URLs. Optional — only needed when STORAGE_S3_ENDPOINT is an internal address not reachable by browsers (e.g. http://minio:9000 in Docker). Set this to the publicly accessible equivalent (e.g. https://storage.example.com).',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @IsOptional()
  STORAGE_S3_PRESIGNED_URL_BASE: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description: 'TTL in seconds for S3 presigned URLs.',
    type: ConfigVariableType.NUMBER,
  })
  @ValidateIf((env) => env.STORAGE_TYPE === StorageDriverType.S_3)
  @CastToPositiveNumber()
  @IsOptional()
  STORAGE_S3_PRESIGNED_URL_EXPIRES_IN: number = 900;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Maximum tarball upload size in bytes for application registration',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  MAX_TARBALL_UPLOAD_SIZE_BYTES: number = 100 * 1024 * 1024;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Maximum bytes of file storage a single workspace may hold, all its files counted. No limit when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  WORKSPACE_STORAGE_LIMIT_BYTES?: number;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.STORAGE_CONFIG,
    description:
      'Maximum number of records a single workspace may hold across its objects, system objects other than messages and calendar events left out, soft-deleted records included. No limit when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  WORKSPACE_RECORD_LIMIT?: number;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'Type of function execution (local or Lambda)',
    type: ConfigVariableType.ENUM,
    options: Object.values(LogicFunctionDriverType),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  LOGIC_FUNCTION_TYPE: LogicFunctionDriverType =
    process.env.NODE_ENV === NodeEnvironment.DEVELOPMENT
      ? LogicFunctionDriverType.LOCAL
      : LogicFunctionDriverType.DISABLED;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'Throttle limit for logic function execution',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  LOGIC_FUNCTION_EXEC_THROTTLE_LIMIT = 1000;

  // milliseconds
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'Time-to-live for logic function execution throttle',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  LOGIC_FUNCTION_EXEC_THROTTLE_TTL = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'Region for AWS Lambda functions',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsAWSRegion()
  LOGIC_FUNCTION_LAMBDA_REGION: AwsRegion;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'IAM role for AWS Lambda functions',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  LOGIC_FUNCTION_LAMBDA_ROLE: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description: 'Role to assume when hosting lambdas in dedicated AWS account',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  LOGIC_FUNCTION_LAMBDA_SUBHOSTING_ROLE?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description:
      'Resource tags applied when creating AWS Lambda functions (JSON object with up to 48 string values)',
    type: ConfigVariableType.JSON,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsLambdaResourceTags()
  LOGIC_FUNCTION_LAMBDA_RESOURCE_TAGS: Record<string, string> = {};

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    isSensitive: true,
    description: 'Access key ID for AWS Lambda functions',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  LOGIC_FUNCTION_LAMBDA_ACCESS_KEY_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    isSensitive: true,
    description: 'Secret access key for AWS Lambda functions',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  LOGIC_FUNCTION_LAMBDA_SECRET_ACCESS_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description:
      'S3 bucket for uploading Lambda layer zip files. Required with the Lambda driver unless STORAGE_S3_NAME is set.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  LOGIC_FUNCTION_LAMBDA_LAYER_BUCKET?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description:
      'AWS region of the S3 bucket for Lambda layer uploads (defaults to LOGIC_FUNCTION_LAMBDA_REGION)',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  @IsAWSRegion()
  LOGIC_FUNCTION_LAMBDA_LAYER_BUCKET_REGION?: AwsRegion;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGIC_FUNCTION_CONFIG,
    description:
      'Custom Lambda endpoint URL. Optional, only needed for Lambda-compatible emulators (e.g. http://floci:4566). Omit for AWS Lambda, where the SDK resolves the endpoint from the region.',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.LOGIC_FUNCTION_TYPE === LogicFunctionDriverType.LAMBDA,
  )
  @IsOptional()
  LOGIC_FUNCTION_LAMBDA_ENDPOINT?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description:
      'Code interpreter driver type - LOCAL for development (unsafe), E2B for sandboxed execution',
    type: ConfigVariableType.STRING,
    options: Object.values(CodeInterpreterDriverType),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  CODE_INTERPRETER_TYPE: CodeInterpreterDriverType =
    process.env.NODE_ENV === NodeEnvironment.DEVELOPMENT
      ? CodeInterpreterDriverType.LOCAL
      : CodeInterpreterDriverType.DISABLED;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description: 'E2B API key for sandboxed code execution',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @ValidateIf(
    (env) => env.CODE_INTERPRETER_TYPE === CodeInterpreterDriverType.E_2_B,
  )
  E2B_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description:
      'E2B template for code interpreter sandboxes; build one with the libraries the PDF and Office skills need using scripts/build-code-interpreter-e2b-template.ts (default: code-interpreter-v1)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  E2B_TEMPLATE: string = 'code-interpreter-v1';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description: 'Timeout in milliseconds for code execution (default: 300000)',
    type: ConfigVariableType.NUMBER,
  })
  @IsOptional()
  @CastToPositiveNumber()
  CODE_INTERPRETER_TIMEOUT_MS = 300_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description:
      'Idle lifetime in milliseconds for a reused code interpreter sandbox; refreshed on each execution and reclaimed after this period of inactivity (default: 300000)',
    type: ConfigVariableType.NUMBER,
  })
  @IsOptional()
  @CastToPositiveNumber()
  CODE_INTERPRETER_IDLE_TIMEOUT_MS = 300_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CODE_INTERPRETER_CONFIG,
    description:
      'Maximum age in milliseconds a reused code interpreter sandbox is kept before garbage collection reclaims it; abandoned conversations are reclaimed after this period (default: 86400000)',
    type: ConfigVariableType.NUMBER,
  })
  @IsOptional()
  @CastToPositiveNumber()
  CODE_INTERPRETER_SESSION_MAX_AGE_MS = 86_400_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ANALYTICS_CONFIG,
    description: 'Enable or disable analytics for telemetry',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  ANALYTICS_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ANALYTICS_CONFIG,
    description: 'Clickhouse host for analytics',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @IsOptional()
  @IsUrl({
    require_tld: false,
    allow_underscores: true,
  })
  @ValidateIf((env) => env.ANALYTICS_ENABLED === true)
  CLICKHOUSE_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ANALYTICS_CONFIG,
    description:
      'Interval in milliseconds between two flushes of the buffered usage rollups',
    type: ConfigVariableType.NUMBER,
  })
  @IsOptional()
  @CastToPositiveNumber()
  USAGE_ROLLUP_FLUSH_INTERVAL_MS = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Enable or disable telemetry logging',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  TELEMETRY_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'TypeORM logging options for development mode. Accepts comma-separated values: query, schema, error, warn, info, log, migration',
    type: ConfigVariableType.ARRAY,
    options: ['query', 'schema', 'error', 'warn', 'info', 'log', 'migration'],
  })
  @CastToTypeORMLogLevelArray()
  @IsOptional()
  TYPEORM_LOGGING: LoggerOptions = ['error'];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description: 'Enable or disable billing features',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_BILLING_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description: 'Link required for billing plan',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_PLAN_REQUIRED_LINK: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Required when billing is enabled. How each billing plan is sold, as {"PRO":{"isDefault":true,"upgradePlanKeys":["ENTERPRISE"]},"ENTERPRISE":{"downgradePlanKeys":["PRO"]}}. Upgrades apply now with proration, downgrades at period end. A plan left out has no switch. The plans some plan can switch to are the two plans on sale, and the one marked isDefault is the default plan at signup',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.JSON,
  })
  @IsBillingPlansConfig()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_PLANS: BillingPlansConfig = {};

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description: 'Duration of free trial with credit card in days',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_FREE_TRIAL_WITH_CREDIT_CARD_DURATION_IN_DAYS = 30;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description: 'Duration of free trial without credit card in days',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_FREE_TRIAL_WITHOUT_CREDIT_CARD_DURATION_IN_DAYS = 7;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Email domains whose users keep the free trial on every workspace, however many trialing workspaces they are already in (twenty.com, acme.com). Exact domain match, subdomains not included',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  BILLING_TRIAL_LIMIT_EXEMPT_EMAIL_DOMAINS: string[] = [];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Amount of credits for the free trial without credit card (in microCredits)',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITHOUT_CREDIT_CARD = 500_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Amount of credits for the free trial with credit card (in microCredits)',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_FREE_WORKFLOW_CREDITS_FOR_TRIAL_PERIOD_WITH_CREDIT_CARD = 2_500_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'User credits each user can spend on AI chat and web search per period of the AI user credit limit default, before workspace credits (in microCredits). No user credits when unset. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  AI_USER_CREDITS_LIMIT?: number;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Quota and stock usage limit default values per billing plan, keyed by plan key then by the default\'s config variable, as {"PRO":{"WORKSPACE_RECORD_LIMIT":1000000},"ENTERPRISE":{"WORKSPACE_RECORD_LIMIT":null},"TRIAL":{"AI_USER_CREDITS_LIMIT":null}}. TRIAL applies to every trialing subscription and wins over its plan. null means no limit, and a variable left out keeps its own value',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.JSON,
  })
  @IsOptional()
  USAGE_LIMIT_DEFAULTS_BY_PLAN: Record<string, PlanUsageLimitDefaults> = {};

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Number of days before a trial WITHOUT a credit card ends to send the reminder to add a payment method',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_TRIAL_WITHOUT_CREDIT_CARD_REMINDER_DAYS_BEFORE = 1;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Number of days before a trial WITH a credit card ends to send the upcoming-charge reminder',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_TRIAL_WITH_CREDIT_CARD_REMINDER_DAYS_BEFORE = 7;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Number of days before a yearly subscription renews to send the renewal reminder',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_SUBSCRIPTION_RENEWAL_REMINDER_DAYS_BEFORE = 7;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    isSensitive: true,
    description: 'Stripe API key for billing',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_STRIPE_API_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    isSensitive: true,
    description: 'Stripe webhook secret for billing',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_STRIPE_WEBHOOK_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Stripe publishable key for billing, exposed to the frontend to mount Stripe Elements',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.IS_BILLING_ENABLED === true)
  BILLING_STRIPE_PUBLISHABLE_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Use the ClickHouse-backed poller (instead of Stripe billing alerts) as the source of truth for metered-credit cap enforcement',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  BILLING_USAGE_CAP_CLICKHOUSE_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Cap on the credits available in a period, as a multiple of the plan allowance. 2 means a workspace can hold at most its allowance plus one full allowance rolled over',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  BILLING_ROLLOVER_TOTAL_CAP_MULTIPLIER = 2;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Largest credit amount a single admin panel grant can hand out (in microCredits)',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsInt()
  @IsOptional()
  BILLING_MAX_ADMIN_CREDIT_GRANT_MICRO = 1_000_000_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Free credits granted for completing the import-contacts onboarding step (in microCredits)',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsInt()
  @IsOptional()
  ONBOARDING_IMPORT_CONTACTS_CREDITS_REWARD = 1_000_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Maximum number of invitations that grant credits during the invite-team onboarding step',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsInt()
  @IsOptional()
  ONBOARDING_INVITE_TEAM_MAX_INVITES = 5;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Free credits granted per user invited during the invite-team onboarding step who signs up (in microCredits)',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsInt()
  @IsOptional()
  ONBOARDING_INVITE_TEAM_CREDITS_REWARD_PER_USER = 500_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.BILLING_CONFIG,
    description:
      'Credit reward tiers for workspaces enrichment matched to a real company, keyed by tier name, as {"midMarket":{"minEmployeeCount":20,"amountMicro":5000000}} (amounts in microCredits). The most generous matching tier wins; no tiers disables the reward. Independent of ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT, so credits and the book-a-call offer can target different companies.',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.JSON,
  })
  @IsOptional()
  ONBOARDING_ENRICHMENT_CREDIT_REWARD_TIERS: Record<
    string,
    OnboardingEnrichmentCreditRewardTier
  > = {};

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Url for the frontend application',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @IsOptional()
  FRONTEND_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Direct HTTPS origin URL for deployments that publish frontend HTML separately. Leave unset for standard self-hosted installations to use bundled HTML.',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
    isHiddenInAdminPanel: true,
  })
  @IsUrl({
    protocols: ['https'],
    require_tld: false,
    require_protocol: true,
  })
  @IsOptional()
  FRONTEND_INDEX_URL: string | undefined;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Default subdomain for the frontend when multi-workspace is enabled',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.IS_MULTIWORKSPACE_ENABLED)
  DEFAULT_SUBDOMAIN = 'app';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Page ID for Cal.com booking integration',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  CALENDAR_BOOKING_PAGE_ID?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Minimum enriched company employee count required to show the book-a-call onboarding step. Leave unset or set to 0 to disable the step. The step also requires CALENDAR_BOOKING_PAGE_ID.',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsInt()
  @IsOptional()
  ONBOARDING_BOOK_CALL_MIN_EMPLOYEE_COUNT?: number;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Enable or disable buffering for logs before sending',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  LOGGER_IS_BUFFER_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Log one line per API request with the actor, the endpoint and the trace ids',
    type: ConfigVariableType.BOOLEAN,
    isEnvOnly: true,
  })
  @IsOptional()
  API_ACCESS_LOG_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Driver used for handling exceptions (Console or Sentry)',
    type: ConfigVariableType.ENUM,
    options: Object.values(ExceptionHandlerDriver),
    isEnvOnly: true,
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  EXCEPTION_HANDLER_DRIVER: ExceptionHandlerDriver =
    ExceptionHandlerDriver.CONSOLE;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Levels of logging to be captured. The "performance" level emits LoggerService perf / perfTime / perfTimeEnd instrumentation.',
    type: ConfigVariableType.ARRAY,
    options: ['log', 'error', 'warn', 'debug', 'verbose', 'performance'],
    isEnvOnly: true,
  })
  @CastToLogLevelArray()
  @IsOptional()
  LOG_LEVELS: TwentyLogLevel[] = ['log', 'error', 'warn', 'performance'];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Driver used for collect metrics (OpenTelemetry or Console)',
    type: ConfigVariableType.ARRAY,
    options: ['OpenTelemetry', 'Console'],
    isEnvOnly: true,
  })
  @CastToMeterDriverArray()
  @IsOptional()
  METER_DRIVER: MeterDriver[] = [];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Interval in milliseconds between two metric exports, for the drivers that push them: opentelemetry and console. The prometheus driver is scraped, so it is unaffected. Read before the config store is available, so it cannot be overridden from the database.',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  METER_EXPORT_INTERVAL_MS = 30_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Temporality of the metrics pushed by the opentelemetry driver: delta sends what changed since the previous export, cumulative sends running totals on every export. Read before the config store is available, so it cannot be overridden from the database.',
    type: ConfigVariableType.ENUM,
    options: Object.values(MeterTemporality),
    isEnvOnly: true,
  })
  @IsOptional()
  @IsEnum(MeterTemporality)
  METER_TEMPORALITY: MeterTemporality = MeterTemporality.Delta;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Driver used for logging (only console for now)',
    type: ConfigVariableType.ENUM,
    options: Object.values(LoggerDriverType),
    isEnvOnly: true,
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  LOGGER_DRIVER: LoggerDriverType = LoggerDriverType.CONSOLE;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Data Source Name (DSN) for Sentry logging',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @ValidateIf(
    (env) => env.EXCEPTION_HANDLER_DRIVER === ExceptionHandlerDriver.SENTRY,
  )
  SENTRY_DSN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Front-end DSN for Sentry logging',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @ValidateIf(
    (env) => env.EXCEPTION_HANDLER_DRIVER === ExceptionHandlerDriver.SENTRY,
  )
  SENTRY_FRONT_DSN: string;
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description: 'Environment name for Sentry logging',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.EXCEPTION_HANDLER_DRIVER === ExceptionHandlerDriver.SENTRY,
  )
  @IsOptional()
  SENTRY_ENVIRONMENT: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Share of front-end traces sent to Sentry, between 0 and 1. Front-end traces propagate their sampling decision to the server, so this also drives the rate for browser-originated server traces.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @Max(1)
  @IsOptional()
  SENTRY_FRONT_TRACES_SAMPLE_RATE = 0.1;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Share of server traces sent to Sentry, between 0 and 1. Browser-originated traces inherit the front-end decision instead, and AI traces are always sampled at 1. Read before the config store is available, so it cannot be overridden from the database.',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  SENTRY_TRACES_SAMPLE_RATE = 0.1;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Share of server processes that profile their sampled traces, between 0 and 1. Read before the config store is available, so it cannot be overridden from the database.',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  SENTRY_PROFILES_SAMPLE_RATE = 0.01;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LOGGING,
    description:
      'Ordered list of sinks the unified event pipeline writes to (e.g. clickhouse). The first is the read store.',
    type: ConfigVariableType.ARRAY,
    isEnvOnly: true,
  })
  @IsOptional()
  EVENT_SINKS: string[] = ['clickhouse'];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SUPPORT_CHAT_CONFIG,
    description: 'Driver used for support chat integration',
    type: ConfigVariableType.ENUM,
    options: Object.values(SupportDriver),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  SUPPORT_DRIVER: SupportDriver = SupportDriver.NONE;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SUPPORT_CHAT_CONFIG,
    isSensitive: true,
    description: 'Chat ID for the support front integration',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.SUPPORT_DRIVER === SupportDriver.FRONT)
  SUPPORT_FRONT_CHAT_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SUPPORT_CHAT_CONFIG,
    isSensitive: true,
    description: 'HMAC key for the support front integration',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.SUPPORT_DRIVER === SupportDriver.FRONT)
  SUPPORT_FRONT_HMAC_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description: 'Database connection URL',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsDefined()
  @IsUrl({
    protocols: ['postgres', 'postgresql'],
    require_tld: false,
    allow_underscores: true,
    require_host: false,
  })
  PG_DATABASE_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description: 'Optional PostgreSQL replica connection URL for read queries',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsOptional()
  @IsUrl({
    protocols: ['postgres', 'postgresql'],
    require_tld: false,
    allow_underscores: true,
    require_host: false,
  })
  PG_DATABASE_REPLICA_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Allow connections to a database with self-signed certificates',
    isEnvOnly: true,
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  PG_SSL_ALLOW_SELF_SIGNED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Maximum number of clients in pg connection pool',
    isEnvOnly: true,
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  PG_POOL_MAX_CONNECTIONS = 10;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Idle timeout in milliseconds for pg connection pool clients',
    isEnvOnly: true,
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  PG_POOL_IDLE_TIMEOUT_MS = 600000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Allow idle pg connection pool clients to exit',
    isEnvOnly: true,
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  PG_POOL_ALLOW_EXIT_ON_IDLE = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Enable configuration variables to be stored in the database',
    isEnvOnly: true,
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_CONFIG_VARIABLES_IN_DB_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.TOKENS_DURATION,
    description: 'Time-to-live for cache storage in seconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  CACHE_STORAGE_TTL: number = 3600 * 24 * 7;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description: 'Redis connection URL used for cache and queues by default',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsUrl({
    protocols: ['redis', 'rediss'],
    require_tld: false,
    allow_underscores: true,
  })
  REDIS_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Optional prefix for cache-storage keys. Empty preserves existing key names. Use a Redis hash tag (e.g. "{twenty-cache}") to place all cache-storage keys in one hash slot and avoid CROSSSLOT errors. Changing it switches cache namespaces and requires all servers and workers to restart with the same value.',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  @IsString()
  REDIS_CACHE_PREFIX: string = '';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description:
      'Optional separate Redis connection for queues with a different eviction policy (advanced production use case, most self-hosters do not need this)',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  @IsUrl({
    protocols: ['redis', 'rediss'],
    require_tld: false,
    allow_underscores: true,
  })
  REDIS_QUEUE_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Key prefix for BullMQ queue keys. Wrap it in curly braces (e.g. "{twenty}") so all keys of a queue share one hash slot when Redis is clustered (Redis Cluster, Redis Enterprise / Azure Managed Redis), otherwise multi-key Lua scripts fail with CROSSSLOT. Changing it orphans jobs stored under the previous prefix.',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  @IsString()
  REDIS_QUEUE_PREFIX: string = 'bull';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Comma-separated list of queues this worker processes (e.g. workspace-queue). Empty means all queues. Used to dedicate worker pods to specific queues.',
    isEnvOnly: true,
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  WORKER_ENABLED_QUEUES: string[] = [];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Comma-separated list of queues this worker does not process (e.g. workspace-queue). Applied after WORKER_ENABLED_QUEUES. Used to keep long-running queues off general-purpose worker pods.',
    isEnvOnly: true,
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  WORKER_EXCLUDED_QUEUES: string[] = [];

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Order the jobs of each queue by tenant virtual clocks (workspace and application group keys) so that a burst from one tenant does not delay the others. Off: jobs of a queue are processed in FIFO order.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_WORKER_FAIRNESS_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Node environment (development, production, etc.)',
    type: ConfigVariableType.ENUM,
    options: Object.values(NodeEnvironment),
    isEnvOnly: true,
  })
  NODE_ENV: NodeEnvironment = NodeEnvironment.PRODUCTION;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Port for the node server',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  NODE_PORT = 3000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Idle keep-alive timeout (ms) for the HTTP server. Should be higher ' +
      'than the idle timeout of any reverse proxy / load balancer in front ' +
      'of it (nginx, ALB, ... default 60s), so the proxy is the side that ' +
      'closes idle connections.',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  SERVER_KEEP_ALIVE_TIMEOUT_MS = 65000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'How long (ms) a worker shutdown waits for active AI chat stream jobs to finish before aborting them into a retryable interrupted state. Must be lower than the pod terminationGracePeriodSeconds so the abort and clean exit fit before SIGKILL (default: 300000)',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  AI_STREAM_SHUTDOWN_DRAIN_MS = 300_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Base URL for the server',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @IsOptional()
  SERVER_URL = 'http://localhost:3000';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Express "trust proxy" setting. Controls whether X-Forwarded-* ' +
      'headers are honored — required for request.protocol to return ' +
      '"https" when TLS is terminated upstream (reverse proxy, ingress, ' +
      'Cloudflare, etc.). Default trusts loopback + RFC1918/ULA peers, ' +
      'which is correct when NestJS runs behind a reverse proxy (our ' +
      'recommended self-host setup). Set to "false" when NestJS is ' +
      'exposed directly to the internet. Accepts any value Express ' +
      'supports — see https://expressjs.com/en/guide/behind-proxies.html.',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsOptional()
  TRUST_PROXY: string = 'loopback, linklocal, uniquelocal';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'Unique identifier for this server instance, generated as UUID v4 during database seeding and persisted in the database. Can be overridden via the environment when IS_CONFIG_VARIABLES_IN_DB_ENABLED is false.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  SERVER_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      "Declares whether this instance is a 'production' (billable per seat) or 'development' (included at no additional cost) enterprise instance. A subscription can register a single free development instance in addition to its production one.",
    type: ConfigVariableType.ENUM,
    options: Object.values(ENTERPRISE_INSTANCE_TYPE),
  })
  @IsOptional()
  @IsIn(Object.values(ENTERPRISE_INSTANCE_TYPE))
  ENTERPRISE_INSTANCE_TYPE: EnterpriseInstanceType =
    ENTERPRISE_INSTANCE_TYPE.PRODUCTION;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Base URL for public domains',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false, require_protocol: true })
  @IsOptional()
  PUBLIC_DOMAIN_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description:
      'ISO date from which HTTP logic functions are no longer served on the legacy /s/ route. Functions created on or after this date are only reachable on the isolated public domain (*.withtwenty.com). Only enforced when PUBLIC_DOMAIN_URL is set; leave empty to keep serving every function on /s/ (default for self-hosting).',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.STRING,
  })
  @IsDateString()
  @IsOptional()
  LOGIC_FUNCTION_LEGACY_ROUTE_CUTOFF: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description: 'Secret key for the application',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  APP_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description:
      'Primary key for at-rest encryption of secrets. Falls back to APP_SECRET when unset.',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  ENCRYPTION_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description:
      'Verification-only fallback key. During rotation, set this to the previous ENCRYPTION_KEY so rows encrypted with the old key remain decryptable and session cookies signed under it still verify.',
    isEnvOnly: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  FALLBACK_ENCRYPTION_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Days the current JWT signing key stays valid before the rotation cron issues a new one. Leave unset to disable auto-rotation.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  SIGNING_KEY_ROTATION_DAYS?: number;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Register the cron job that syncs the marketplace catalog from the npm registry. Disable to stop the automatic catalog import.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  MARKETPLACE_CATALOG_SYNC_CRON_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Maximum number of records affected by mutations',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  MUTATION_MAXIMUM_AFFECTED_RECORDS = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Time-to-live for short API rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  API_RATE_LIMITING_SHORT_TTL_IN_MS = 1000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of requests allowed in the short rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  API_RATE_LIMITING_SHORT_LIMIT = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Time-to-live for long API rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  API_RATE_LIMITING_LONG_TTL_IN_MS = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of requests allowed in the long rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  API_RATE_LIMITING_LONG_LIMIT = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for per-application API rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  APPLICATION_API_RATE_LIMITING_TTL_IN_MS = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of API requests allowed per application across all workspaces in the rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  APPLICATION_API_RATE_LIMITING_LIMIT = 500;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for outbound email send rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SEND_RATE_LIMITING_TTL_IN_MS = 10_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of emails sent across all workspaces in the rate limiting window. Set it below the send rate the email provider publishes for the account, so transactional mail sharing that account keeps headroom during a campaign',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SEND_RATE_LIMITING_LIMIT = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of emails a single workspace may send per UTC day, campaign and one-off sends counted together. USAGE_LIMIT_DEFAULTS_BY_PLAN can set it per billing plan, and a workspace limit configured in the app replaces it',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SEND_WORKSPACE_DAILY_LIMIT = 1_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for the per-workspace outbound email send rate limiting window, in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SEND_WORKSPACE_RATE_LIMITING_TTL_IN_MS = 10_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of emails a single workspace may send in the rate limiting window. Applies on top of the server-wide limit, so set it below that one to stop a single workspace consuming the whole instance budget with one campaign. Left equal to the server-wide limit it never binds first',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  EMAIL_SEND_WORKSPACE_RATE_LIMITING_LIMIT = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for the outbound webhook call rate limiting window, in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WEBHOOK_CALL_RATE_LIMITING_TTL_IN_MS = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of outbound webhook calls a single workspace may make in the rate limiting window. Calls above it are never enqueued and are recorded as a failed webhook response',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WEBHOOK_CALL_RATE_LIMITING_LIMIT = 60;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for application job enqueue rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  APPLICATION_JOB_ENQUEUE_RATE_LIMITING_TTL_IN_MS = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of jobs a single application installation can enqueue in the rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  APPLICATION_JOB_ENQUEUE_RATE_LIMITING_LIMIT = 500;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of jobs enqueued per application registration across all workspaces in the rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  APPLICATION_REGISTRATION_JOB_ENQUEUE_RATE_LIMITING_LIMIT = 2000;

  @CastToPositiveNumber()
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Maximum fields allowed for GQL queries',
    type: ConfigVariableType.NUMBER,
  })
  GRAPHQL_MAX_FIELDS = 2000;

  @CastToPositiveNumber()
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Maximum root resolvers allowed for GQL queries',
    type: ConfigVariableType.NUMBER,
  })
  GRAPHQL_MAX_ROOT_RESOLVERS = 20;

  @CastToPositiveNumber()
  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description: 'Maximum complexity allowed for Common API queries',
    type: ConfigVariableType.NUMBER,
  })
  COMMON_QUERY_COMPLEXITY_LIMIT = 2000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for workspace-level invitations resending rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  INVITATION_SENDING_BY_WORKSPACE_THROTTLE_TTL_IN_MS = 604_800_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of workspace-level invitations resending allowed in the rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  INVITATION_SENDING_BY_WORKSPACE_THROTTLE_LIMIT = 500;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for email-level invitations sending rate limiting in milliseconds',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  INVITATION_SENDING_BY_EMAIL_THROTTLE_TTL_IN_MS = 604_800_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Maximum number of email-level invitations sending allowed in the rate limiting window',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  INVITATION_SENDING_BY_EMAIL_THROTTLE_LIMIT = 10;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SSL,
    description: 'Path to the SSL key for enabling HTTPS in local development',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsOptional()
  SSL_KEY_PATH: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SSL,
    description:
      'Path to the SSL certificate for enabling HTTPS in local development',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
  })
  @IsOptional()
  SSL_CERT_PATH: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    isSensitive: true,
    description: 'API key for Cloudflare integration',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.CLOUDFLARE_ZONE_ID)
  CLOUDFLARE_API_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    description: 'Zone ID for Cloudflare integration',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.CLOUDFLARE_API_KEY)
  CLOUDFLARE_ZONE_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    description: 'Zone ID for public domain Cloudflare integration',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf((env) => env.PUBLIC_DOMAIN_URL)
  CLOUDFLARE_PUBLIC_DOMAIN_ZONE_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    description: 'Random string to validate queries from Cloudflare',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @IsOptional()
  CLOUDFLARE_WEBHOOK_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    description:
      'Id to generate value for CNAME record to validate ownership and manage ssl for custom hostname with Cloudflare',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  CLOUDFLARE_DCV_DELEGATION_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CLOUDFLARE_CONFIG,
    description:
      'Store the visitor location headers Cloudflare adds (cf-ipcountry, ' +
      'cf-region, cf-ipcity) on user sessions. Only enable when every ' +
      'request reaches the server through Cloudflare: otherwise clients ' +
      'can forge them.',
    type: ConfigVariableType.BOOLEAN,
    isEnvOnly: true,
  })
  @IsOptional()
  IS_CLOUDFLARE_GEOLOCATION_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for OpenAI models (GPT, o-series)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  OPENAI_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for Anthropic models (Claude)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  ANTHROPIC_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for Google AI models (Gemini)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  GOOGLE_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for xAI models (Grok)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  XAI_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for Groq inference',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  GROQ_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for Mistral models',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  MISTRAL_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description: 'API key for TypeSafe AI classification models (Jev)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  TYPESAFE_AI_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    isSensitive: true,
    description:
      'AI provider configurations. An entry with the same name as a built-in provider (ai-providers.json) replaces it and keeps only the models it lists. Use for custom endpoints, extra regions, or credentials set via admin panel.',
    type: ConfigVariableType.JSON,
  })
  @IsOptional()
  AI_PROVIDERS: AiProvidersConfig = {};

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Storage path for the AI catalog override (e.g. config/ai-catalog.json). When set, the catalog is fetched from the configured storage backend at startup instead of using the built-in ai-providers.json.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  AI_CATALOG_STORAGE_PATH?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ordered list of model IDs backing the Extra Fast tier; the first available one is used. An ID may pin an effort level as provider/model@effort. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_EXTRA_FAST: string[] = DEFAULT_MODELS_BY_TIER.extraFast;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ordered list of model IDs backing the Fast tier; the first available one is used. An ID may pin an effort level as provider/model@effort. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_FAST: string[] = DEFAULT_MODELS_BY_TIER.fast;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ordered list of model IDs backing the Balanced tier; the first available one is used. An ID may pin an effort level as provider/model@effort. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_BALANCED: string[] = DEFAULT_MODELS_BY_TIER.balanced;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ordered list of model IDs backing the Smart tier; the first available one is used. An ID may pin an effort level as provider/model@effort. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_SMART: string[] = DEFAULT_MODELS_BY_TIER.smart;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ordered list of model IDs backing the Extra Smart tier; the first available one is used. An ID may pin an effort level as provider/model@effort. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_EXTRA_SMART: string[] = DEFAULT_MODELS_BY_TIER.extraSmart;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'List of model IDs disabled by default. Disabled models cannot be used by any workspace. Managed via admin panel or env.',
    type: ConfigVariableType.ARRAY,
  })
  @IsOptional()
  AI_MODELS_DEFAULT_DISABLED: string[] = DEFAULT_DISABLED_MODELS;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.LLM,
    description:
      'Ask OpenAI and Azure reasoning models for reasoning summaries in AI chat. Disable it if your OpenAI organization is not verified, since OpenAI rejects these requests.',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_OPENAI_REASONING_SUMMARY_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Enable or disable multi-workspace support',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_MULTIWORKSPACE_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Number of inactive days before sending a deletion warning for workspaces. Used in the workspace deletion cron job to determine when to send warning emails.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsStrictlyLowerThan('WORKSPACE_INACTIVE_DAYS_BEFORE_SOFT_DELETION', {
    message:
      '"WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION" should be strictly lower than "WORKSPACE_INACTIVE_DAYS_BEFORE_SOFT_DELETION"',
  })
  WORKSPACE_INACTIVE_DAYS_BEFORE_NOTIFICATION = 7;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Number of inactive days before soft deleting workspaces',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsStrictlyLowerThan('WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION', {
    message:
      '"WORKSPACE_INACTIVE_DAYS_BEFORE_SOFT_DELETION" should be strictly lower than "WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION"',
  })
  WORKSPACE_INACTIVE_DAYS_BEFORE_SOFT_DELETION = 14;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Number of inactive days before deleting workspaces',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WORKSPACE_INACTIVE_DAYS_BEFORE_DELETION = 21;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Maximum number of workspaces that can be deleted in a single execution',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @ValidateIf((env) => env.MAX_NUMBER_OF_WORKSPACES_DELETED_PER_EXECUTION > 0)
  MAX_NUMBER_OF_WORKSPACES_DELETED_PER_EXECUTION = 5;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Throttle limit for workflow execution. Remaining will not be enqueued immediately.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WORKFLOW_EXEC_SOFT_THROTTLE_LIMIT = 100;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for workflow execution throttle in milliseconds. Remaining will not be enqueued immediately.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WORKFLOW_EXEC_SOFT_THROTTLE_TTL = 60_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Throttle limit for workflow execution. Remaining will be marked as failed.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WORKFLOW_EXEC_HARD_THROTTLE_LIMIT = 5000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RATE_LIMITING,
    description:
      'Time-to-live for workflow execution throttle in milliseconds. Remaining will be marked as failed.',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  WORKFLOW_EXEC_HARD_THROTTLE_TTL = 3_600_000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CAPTCHA_CONFIG,
    description: 'Driver for captcha integration',
    type: ConfigVariableType.ENUM,
    options: Object.values(CaptchaDriverType),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  CAPTCHA_DRIVER?: CaptchaDriverType;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CAPTCHA_CONFIG,
    isSensitive: true,
    description: 'Site key for captcha integration',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  CAPTCHA_SITE_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CAPTCHA_CONFIG,
    isSensitive: true,
    description: 'Secret key for captcha integration',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  CAPTCHA_SECRET_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CAPTCHA_CONFIG,
    description:
      'Minimum Google reCAPTCHA v3 score, between 0 and 1, required to accept a request',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  CAPTCHA_MIN_SCORE = 0;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.CAPTCHA_CONFIG,
    description: 'Require a valid captcha to create a new workspace',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_WORKSPACE_CREATION_CAPTCHA_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    isSensitive: true,
    description: 'License key for the Enterprise version',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  ENTERPRISE_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description:
      'Signed enterprise validity token (JWT). Used as fallback when no token is stored in the database.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  ENTERPRISE_VALIDITY_TOKEN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Base URL for the Enterprise API on twenty.com',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  ENTERPRISE_API_URL: string = 'https://twenty.com/api/enterprise';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Health monitoring time window in minutes',
    type: ConfigVariableType.NUMBER,
  })
  @CastToPositiveNumber()
  @IsOptional()
  HEALTH_METRICS_TIME_WINDOW_IN_MINUTES = 5;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Enable or disable the attachment preview feature',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_ATTACHMENT_PREVIEW_ENABLED = true;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.SERVER_CONFIG,
    description: 'Twenty server version',
    type: ConfigVariableType.STRING,
    isEnvOnly: true,
    isHiddenInAdminPanel: true,
  })
  @IsOptionalOrEmptyString()
  @IsTwentySemVer()
  APP_VERSION?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Enable or disable address autocomplete (see ADDRESS_AUTOCOMPLETE_DRIVER)',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_MAPS_AND_ADDRESS_AUTOCOMPLETE_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Address autocomplete driver: GOOGLE_PLACES (worldwide, requires GOOGLE_MAP_API_KEY) or BASE_ADRESSE_NATIONALE (French national address database, France only, no key needed)',
    type: ConfigVariableType.ENUM,
    options: Object.values(ADDRESS_AUTOCOMPLETE_DRIVER_TYPE),
  })
  @IsOptional()
  @CastToUpperSnakeCase()
  @IsIn(Object.values(ADDRESS_AUTOCOMPLETE_DRIVER_TYPE))
  ADDRESS_AUTOCOMPLETE_DRIVER: AddressAutocompleteDriverType =
    ADDRESS_AUTOCOMPLETE_DRIVER_TYPE.GOOGLE_PLACES;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description: 'Google map api key for places and map',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) =>
      env.IS_MAPS_AND_ADDRESS_AUTOCOMPLETE_ENABLED &&
      env.ADDRESS_AUTOCOMPLETE_DRIVER ===
        ADDRESS_AUTOCOMPLETE_DRIVER_TYPE.GOOGLE_PLACES,
  )
  GOOGLE_MAP_API_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description:
      'API key for People Data Labs company enrichment. When unset, workspace company enrichment is skipped.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  PEOPLE_DATA_LABS_API_KEY?: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Enable or disable the AI chat that helps set up the workspace at the end of onboarding',
    type: ConfigVariableType.BOOLEAN,
  })
  @IsOptional()
  IS_ONBOARDING_AI_CHAT_ENABLED = false;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'Driver used for the emailing domain feature — AWS_SES (requires AWS credentials), RESEND (requires a Resend API key), LOG fakes registration/verification/sends locally',
    type: ConfigVariableType.ENUM,
    options: Object.values(EmailingDomainDriver),
    isEnvOnly: true,
  })
  @CastToUpperSnakeCase()
  EMAILING_DOMAIN_DRIVER: EmailingDomainDriver = EmailingDomainDriver.LOG;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description: 'AWS region',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.EMAILING_DOMAIN_DRIVER === EmailingDomainDriver.AWS_SES,
  )
  @IsAWSRegion()
  @IsNotEmpty()
  AWS_SES_REGION: AwsRegion;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    isSensitive: true,
    description: 'AWS access key ID',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  AWS_SES_ACCESS_KEY_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    isSensitive: true,
    description: 'AWS session token',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  AWS_SES_SESSION_TOKEN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    isSensitive: true,
    description: 'AWS secret access key',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  AWS_SES_SECRET_ACCESS_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description: 'AWS Account ID for SES ARN construction',
    type: ConfigVariableType.STRING,
  })
  @ValidateIf(
    (env) => env.EMAILING_DOMAIN_DRIVER === EmailingDomainDriver.AWS_SES,
  )
  @IsString()
  @IsNotEmpty()
  AWS_SES_ACCOUNT_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'Domain used for email group inbound mail (the right-hand side of ch_xxx@<domain>). Required to enable email group channels.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  INBOUND_EMAIL_DOMAIN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'Comma-separated list of SNS topic ARNs accepted by the inbound-email and outbound-event webhooks (e.g. arn:aws:sns:us-east-1:123:my-inbound). Every SNS payload whose topic is absent from this list is rejected.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  @IsString()
  SES_SNS_TOPIC_ARN_ALLOWLIST: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'SNS topic ARN that receives SES DELIVERY, BOUNCE, COMPLAINT, REJECT and RENDERING_FAILURE events. An SNS event destination pointing at it is added to each workspace SES configuration set, and the topic must be subscribed to /webhooks/messaging/ses/outbound. Bounces and complaints also arrive through the pre-existing EventBridge destination, so those two are delivered twice and deduplicated downstream.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  @IsString()
  SES_OUTBOUND_SNS_TOPIC_ARN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'Tatami Monitor ingest webhook URL (SNS HTTPS subscription target for deliverability observability).',
    type: ConfigVariableType.STRING,
    isSensitive: true,
  })
  @IsOptional()
  TATAMI_SES_WEBHOOK_URL: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.AWS_SES_SETTINGS,
    description:
      'SNS topic ARN that fans out SES events to Tatami Monitor. When set, an SNS event destination is added to each workspace SES configuration set.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  TATAMI_SNS_TOPIC_ARN: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RESEND_SETTINGS,
    isSensitive: true,
    description: 'Resend API key used when EMAILING_DOMAIN_DRIVER is RESEND',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  RESEND_API_KEY: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RESEND_SETTINGS,
    isSensitive: true,
    description:
      'Signing secret of the Resend webhook endpoint that targets /webhooks/messaging/resend (whsec_...)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  RESEND_WEBHOOK_SIGNING_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.RESEND_SETTINGS,
    description:
      'Region Resend provisions new emailing domains in (us-east-1, eu-west-1, sa-east-1 or ap-northeast-1). Leave empty for the Resend default.',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  RESEND_DOMAIN_REGION: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Timeout in milliseconds for primary database queries',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  PG_DATABASE_PRIMARY_TIMEOUT_MS: number = 10000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description: 'Timeout in milliseconds for replica database queries',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  PG_DATABASE_REPLICA_TIMEOUT_MS: number = 10000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Timeout in milliseconds for the search ILIKE fallback query per searchable object. Triggered only for input containing CJK characters when the tsvector query returns 0 results on the first page. When the timeout fires the fallback is skipped for that object.',
    type: ConfigVariableType.NUMBER,
    isEnvOnly: true,
  })
  @CastToPositiveNumber()
  @IsOptional()
  SEARCH_ILIKE_FALLBACK_TIMEOUT_MS: number = 2000;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Default npm registry URL for resolving app packages (e.g. https://registry.npmjs.org)',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false })
  @IsOptional()
  APP_REGISTRY_URL: string = 'https://registry.npmjs.org';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'CDN base URL for serving files from registry (e.g. https://unpkg.com)',
    type: ConfigVariableType.STRING,
  })
  @IsUrl({ require_tld: false })
  @IsOptional()
  APP_REGISTRY_CDN_URL: string = 'https://unpkg.com';

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    description:
      'Client ID of the GitHub OAuth app used to verify app ownership when claiming a marketplace application',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.STRING,
  })
  @IsString()
  @IsOptional()
  APP_CLAIM_GITHUB_CLIENT_ID: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description:
      'Client secret of the GitHub OAuth app used to verify app ownership when claiming a marketplace application',
    isHiddenInAdminPanel: true,
    type: ConfigVariableType.STRING,
  })
  @IsString()
  @IsOptional()
  APP_CLAIM_GITHUB_CLIENT_SECRET: string;

  @ConfigVariablesMetadata({
    group: ConfigVariablesGroup.ADVANCED_SETTINGS,
    isSensitive: true,
    description:
      'Auth token for the default npm registry (for private packages)',
    type: ConfigVariableType.STRING,
  })
  @IsOptional()
  APP_REGISTRY_TOKEN: string;
}

export const validate = (config: Record<string, unknown>): ConfigVariables => {
  const validatedConfig = plainToClass(ConfigVariables, config);

  const validationErrors = validateSync(validatedConfig, {
    strictGroups: true,
  });

  const validationWarnings = validateSync(validatedConfig, {
    groups: ['warning'],
  });
  const logValidatonErrors = (
    errorCollection: ValidationError[],
    type: 'error' | 'warn',
  ) =>
    errorCollection.forEach((error) => {
      if (!isDefined(error.constraints) || !isDefined(error.property)) {
        return;
      }
      Logger[type](Object.values(error.constraints).join('\n'));
    });

  if (validationWarnings.length > 0) {
    logValidatonErrors(validationWarnings, 'warn');
  }

  if (validationErrors.length > 0) {
    logValidatonErrors(validationErrors, 'error');
    throw new ConfigVariableException(
      'Config variables validation failed',
      ConfigVariableExceptionCode.VALIDATION_FAILED,
    );
  }

  return validatedConfig;
};