/**
 * Contact System Configuration
 *
 * Central configuration file for all contact form settings.
 * Modify values here to change system behavior without touching code.
 *
 * @module lib/config/contact.config
 */

/**
 * Rate limiting configuration for contact form submissions
 *
 * Prevents abuse and spam by limiting submission frequency per IP address
 */
export const CONTACT_RATE_LIMIT = {
  /** Maximum submissions allowed within time window */
  MAX_REQUESTS: 3,

  /** Time window for rate limit (sliding window) */
  WINDOW: "5 m", // 5 minutes

  /** Redis key prefix for rate limit storage */
  PREFIX: "contact-form",

  /** Whether rate limiting is enabled */
  ENABLED: process.env.UPSTASH_REDIS_REST_URL !== undefined,
} as const;

/**
 * Validation rules for contact form fields
 *
 * Change these values to adjust validation requirements
 */
export const CONTACT_VALIDATION = {
  name: {
    /** Minimum length for name field */
    minLength: 2,

    /** Maximum length for name field */
    maxLength: 100,

    /** Whether name is required */
    required: true,
  },

  email: {
    /** Whether email is required */
    required: true,

    /** Maximum length for email */
    maxLength: 255,
  },

  phone: {
    /** Whether phone is required */
    required: false,

    /** Maximum length for phone */
    maxLength: 50,
  },

  company: {
    /** Whether company is required */
    required: false,

    /** Maximum length for company name */
    maxLength: 255,
  },

  message: {
    /** Minimum length for message */
    minLength: 10,

    /** Maximum length for message */
    maxLength: 10000,

    /** Whether message is required */
    required: true,
  },

  topic: {
    /** Whether topic is required */
    required: true,

    /** Allowed topic values */
    allowedValues: [
      "sales",
      "support",
      "billing",
      "partnerships",
      "press",
      "careers",
      "security",
      "demo",
      "other",
    ] as const,
  },

  language: {
    /** Allowed language codes */
    allowedValues: ["ar", "en"] as const,

    /** Default language if not specified */
    default: "en" as const,
  },

  consent: {
    /** Whether consent checkbox must be checked */
    required: true,
  },
} as const;

/**
 * File upload configuration
 *
 * Settings for contact form file attachments
 */
export const CONTACT_FILE_UPLOAD = {
  /** Maximum number of files per submission */
  maxFiles: 3,

  /** Maximum file size in bytes (10MB) */
  maxSizeBytes: 10 * 1024 * 1024,

  /** Allowed file extensions */
  allowedExtensions: [
    ".jpg",
    ".jpeg",
    ".png",
    ".gif",
    ".webp",
    ".pdf",
  ] as const,

  /** Allowed MIME types */
  allowedMimeTypes: [
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp",
    "application/pdf",
  ] as const,

  /** Storage bucket name for attachments */
  bucketName: "contact-attachments",
} as const;

/**
 * reCAPTCHA configuration
 *
 * Bot protection settings for contact form
 */
export const CONTACT_RECAPTCHA = {
  /** Whether reCAPTCHA is enabled */
  enabled: process.env.RECAPTCHA_SECRET_KEY !== undefined,

  /** Minimum score required (0.0 to 1.0) */
  scoreThreshold: parseFloat(process.env.RECAPTCHA_SCORE_THRESHOLD || "0.5"),

  /** reCAPTCHA site key (public) */
  siteKey: process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY,

  /** Allow bypass for testing */
  allowTestBypass: process.env.NODE_ENV === "development",

  /** Test bypass token */
  testBypassToken: "DISABLED_FOR_TESTING",
} as const;

/**
 * Contact status configuration
 *
 * Defines available statuses and their properties
 */
export const CONTACT_STATUSES = {
  NEW: {
    label: "New",
    color: "blue",
    description: "Newly submitted, not yet viewed",
    allowedNextStatuses: ["READ", "IN_PROGRESS", "SPAM"],
  },
  READ: {
    label: "Read",
    color: "gray",
    description: "Viewed by staff but no action taken",
    allowedNextStatuses: ["IN_PROGRESS", "CLOSED", "SPAM"],
  },
  IN_PROGRESS: {
    label: "In Progress",
    color: "yellow",
    description: "Staff is working on response",
    allowedNextStatuses: ["RESPONDED", "CLOSED"],
  },
  RESPONDED: {
    label: "Responded",
    color: "green",
    description: "Response has been sent",
    allowedNextStatuses: ["IN_PROGRESS", "CLOSED"],
  },
  CLOSED: {
    label: "Closed",
    color: "gray",
    description: "Issue resolved and closed",
    allowedNextStatuses: ["IN_PROGRESS"], // Can reopen
  },
  SPAM: {
    label: "Spam",
    color: "red",
    description: "Marked as spam",
    allowedNextStatuses: ["NEW"], // Can undo spam marking
  },
} as const;

/**
 * Database configuration for contact system
 *
 * Defines which database is used (Convex via Prisma adapter)
 */
export const CONTACT_DATABASES = {
  /** Primary database (Convex via Prisma adapter) */
  primary: {
    name: "Convex",
    tableName: "contacts",
    purpose: "Staff dashboard, contact management, source of truth",
  },

  /** Which database is source of truth */
  sourceOfTruth: "primary" as const,
} as const;

/**
 * Auto-assignment rules (future enhancement)
 *
 * Rules for automatically assigning contacts to staff based on topic
 */
export const CONTACT_AUTO_ASSIGNMENT = {
  /** Whether auto-assignment is enabled */
  enabled: false,

  /** Topic to staff role mapping */
  topicAssignment: {
    sales: "sales_team",
    support: "support_team",
    billing: "billing_team",
    partnerships: "partnerships_team",
    security: "security_team",
    demo: "sales_team",
    press: "marketing_team",
    careers: "hr_team",
    other: "support_team",
  },
} as const;

/**
 * Response time SLA configuration
 *
 * Service Level Agreement for response times
 */
export const CONTACT_SLA = {
  /** Standard response time (hours) */
  standardResponseTime: 24,

  /** Urgent response time (hours) for security/critical topics */
  urgentResponseTime: 4,

  /** Topics that require urgent response */
  urgentTopics: ["security", "billing"],

  /** Whether to send auto-acknowledgment email */
  sendAutoAcknowledgment: true,

  /** Auto-acknowledgment email template */
  acknowledgmentTemplate: "contact-acknowledgment",
} as const;

/**
 * Notification configuration
 *
 * Settings for notifying staff about new submissions
 */
export const CONTACT_NOTIFICATIONS = {
  /** Whether to notify staff on new submissions */
  enabled: process.env.CONTACT_NOTIFICATIONS_ENABLED === "true",

  /** Notification channels */
  channels: {
    email: true,
    slack: false, // Enable when Slack webhook configured
    sms: false, // Enable when SMS service configured
  },

  /** Email addresses to notify */
  notifyEmails: [
    process.env.CONTACT_NOTIFICATION_EMAIL || "support@mawidi.com",
  ],

  /** Slack webhook URL (if enabled) */
  slackWebhook: process.env.SLACK_CONTACT_WEBHOOK_URL,

  /** Whether to batch notifications */
  batchNotifications: false,

  /** Batch interval (minutes) if batching enabled */
  batchInterval: 15,
} as const;

/**
 * CORS configuration for contact API
 */
export const CONTACT_CORS = {
  /** Allowed origins */
  allowedOrigins: process.env.NEXT_PUBLIC_APP_URL || "*",

  /** Allowed methods */
  allowedMethods: "POST, OPTIONS",

  /** Allowed headers */
  allowedHeaders: "Content-Type",

  /** Max age for preflight cache (seconds) */
  maxAge: "86400", // 24 hours
} as const;

/**
 * Pagination configuration for staff dashboard
 */
export const CONTACT_PAGINATION = {
  /** Default number of items per page */
  defaultPerPage: 25,

  /** Maximum items per page */
  maxPerPage: 100,

  /** Minimum items per page */
  minPerPage: 10,
} as const;

/**
 * Search configuration for contact filtering
 */
export const CONTACT_SEARCH = {
  /** Minimum search query length */
  minQueryLength: 2,

  /** Maximum search query length */
  maxQueryLength: 100,

  /** Fields to search in */
  searchableFields: ["name", "email", "company", "message"] as const,

  /** Whether search is case-sensitive */
  caseSensitive: false,
} as const;

/**
 * Get all configuration as a single object
 * Useful for debugging and documentation
 */
export const CONTACT_CONFIG = {
  rateLimit: CONTACT_RATE_LIMIT,
  validation: CONTACT_VALIDATION,
  fileUpload: CONTACT_FILE_UPLOAD,
  recaptcha: CONTACT_RECAPTCHA,
  statuses: CONTACT_STATUSES,
  databases: CONTACT_DATABASES,
  autoAssignment: CONTACT_AUTO_ASSIGNMENT,
  sla: CONTACT_SLA,
  notifications: CONTACT_NOTIFICATIONS,
  cors: CONTACT_CORS,
  pagination: CONTACT_PAGINATION,
  search: CONTACT_SEARCH,
} as const;

/**
 * Get configuration value by path
 *
 * @param path - Dot-notation path to config value
 * @returns Configuration value
 *
 * @example
 * ```typescript
 * const maxLength = getConfig('validation.name.maxLength'); // 100
 * ```
 */
export function getConfig(path: string): any {
  return path.split(".").reduce((obj: any, key) => obj?.[key], CONTACT_CONFIG);
}
