/**
 * System-wide Configuration
 * Central configuration file for the Royal Enfield Workflow Management System
 * All settings can be overridden via environment variables
 */

export const SYSTEM_CONFIG = {
  // Application Information
  APP_NAME: 'Royal Enfield Workflow Management',
  APP_VERSION: '1.2.0',
  APP_ENV: process.env.NODE_ENV || 'development',
  
  // Working Hours Configuration
  WORKING_HOURS: {
    START_HOUR: parseInt(process.env.WORK_START_HOUR || '9', 10),
    END_HOUR: parseInt(process.env.WORK_END_HOUR || '18', 10),
    START_DAY: 1, // Monday
    END_DAY: 5,   // Friday
    TIMEZONE: process.env.TZ || 'Asia/Kolkata',
  },
  
  // TAT (Turnaround Time) Settings
  TAT: {
    // Notification thresholds (percentage)
    THRESHOLD_50_PERCENT: 50,
    THRESHOLD_75_PERCENT: 75,
    THRESHOLD_100_PERCENT: 100,
    
    // Test mode for faster testing
    TEST_MODE: process.env.TAT_TEST_MODE === 'true',
    TEST_TIME_MULTIPLIER: process.env.TAT_TEST_MODE === 'true' ? 1/60 : 1, // 1 hour = 1 minute in test mode
    
    // Default TAT values by priority (in hours)
    DEFAULT_EXPRESS_TAT: parseInt(process.env.DEFAULT_EXPRESS_TAT || '24', 10),
    DEFAULT_STANDARD_TAT: parseInt(process.env.DEFAULT_STANDARD_TAT || '72', 10),
  },
  
  // File Upload Limits
  UPLOAD: {
    MAX_FILE_SIZE_MB: parseInt(process.env.MAX_FILE_SIZE_MB || '10', 10),
    MAX_FILE_SIZE_BYTES: parseInt(process.env.MAX_FILE_SIZE_MB || '10', 10) * 1024 * 1024,
    ALLOWED_FILE_TYPES: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif', 'txt'],
    MAX_FILES_PER_REQUEST: parseInt(process.env.MAX_FILES_PER_REQUEST || '10', 10),
  },
  
  // Workflow Limits
  WORKFLOW: {
    MAX_APPROVAL_LEVELS: parseInt(process.env.MAX_APPROVAL_LEVELS || '10', 10),
    MAX_PARTICIPANTS: parseInt(process.env.MAX_PARTICIPANTS_PER_REQUEST || '50', 10),
    MAX_SPECTATORS: parseInt(process.env.MAX_SPECTATORS || '20', 10),
    MIN_APPROVAL_LEVELS: 1,
  },
  
  // Work Notes Configuration
  WORK_NOTES: {
    MAX_MESSAGE_LENGTH: parseInt(process.env.MAX_MESSAGE_LENGTH || '2000', 10),
    MAX_ATTACHMENTS_PER_NOTE: parseInt(process.env.MAX_ATTACHMENTS_PER_NOTE || '5', 10),
    ENABLE_REACTIONS: process.env.ENABLE_REACTIONS !== 'false',
    ENABLE_MENTIONS: process.env.ENABLE_MENTIONS !== 'false',
  },
  
  // Pagination
  PAGINATION: {
    DEFAULT_PAGE_SIZE: parseInt(process.env.DEFAULT_PAGE_SIZE || '20', 10),
    MAX_PAGE_SIZE: parseInt(process.env.MAX_PAGE_SIZE || '100', 10),
  },
  
  // Session & Security
  SECURITY: {
    SESSION_TIMEOUT_MINUTES: parseInt(process.env.SESSION_TIMEOUT_MINUTES || '30', 10),
    JWT_EXPIRY: process.env.JWT_EXPIRY || '30m',
    ENABLE_2FA: process.env.ENABLE_2FA === 'true',
  },
  
  // Notification Settings
  NOTIFICATIONS: {
    ENABLE_EMAIL: process.env.ENABLE_EMAIL_NOTIFICATIONS !== 'false',
    ENABLE_PUSH: process.env.ENABLE_PUSH_NOTIFICATIONS !== 'false',
    ENABLE_IN_APP: true, // Always enabled
    BATCH_DELAY_MS: parseInt(process.env.NOTIFICATION_BATCH_DELAY || '5000', 10),
  },
  
  // Feature Flags
  FEATURES: {
    ENABLE_AI_CONCLUSION: process.env.ENABLE_AI_CONCLUSION !== 'false',
    ENABLE_TEMPLATES: process.env.ENABLE_TEMPLATES === 'true', // Future feature
    ENABLE_ANALYTICS: process.env.ENABLE_ANALYTICS !== 'false',
    ENABLE_EXPORT: process.env.ENABLE_EXPORT !== 'false',
  },
  
  // Redis & Queue
  REDIS: {
    URL: process.env.REDIS_URL || 'redis://localhost:6379',
    QUEUE_CONCURRENCY: parseInt(process.env.QUEUE_CONCURRENCY || '5', 10),
    RATE_LIMIT_MAX: parseInt(process.env.RATE_LIMIT_MAX || '10', 10),
    RATE_LIMIT_DURATION: parseInt(process.env.RATE_LIMIT_DURATION || '1000', 10),
  },
  
  // UI Preferences (can be overridden per user in future)
  UI: {
    DEFAULT_THEME: 'light',
    DEFAULT_LANGUAGE: 'en',
    DATE_FORMAT: 'DD/MM/YYYY',
    TIME_FORMAT: '12h', // or '24h'
    CURRENCY: 'INR',
    CURRENCY_SYMBOL: '₹',
  },
};

/**
 * Get configuration for frontend consumption
 * Returns only non-sensitive configuration values
 */
export async function getPublicConfig() {
  // Get base configuration
  const baseConfig = {
    appName: SYSTEM_CONFIG.APP_NAME,
    appVersion: SYSTEM_CONFIG.APP_VERSION,
    workingHours: SYSTEM_CONFIG.WORKING_HOURS,
    tat: {
      thresholds: {
        warning: SYSTEM_CONFIG.TAT.THRESHOLD_50_PERCENT,
        critical: SYSTEM_CONFIG.TAT.THRESHOLD_75_PERCENT,
        breach: SYSTEM_CONFIG.TAT.THRESHOLD_100_PERCENT,
      },
      testMode: SYSTEM_CONFIG.TAT.TEST_MODE,
    },
    upload: {
      maxFileSizeMB: SYSTEM_CONFIG.UPLOAD.MAX_FILE_SIZE_MB,
      allowedFileTypes: SYSTEM_CONFIG.UPLOAD.ALLOWED_FILE_TYPES,
      maxFilesPerRequest: SYSTEM_CONFIG.UPLOAD.MAX_FILES_PER_REQUEST,
    },
    workflow: {
      maxApprovalLevels: SYSTEM_CONFIG.WORKFLOW.MAX_APPROVAL_LEVELS,
      maxParticipants: SYSTEM_CONFIG.WORKFLOW.MAX_PARTICIPANTS,
      maxSpectators: SYSTEM_CONFIG.WORKFLOW.MAX_SPECTATORS,
    },
    workNotes: {
      maxMessageLength: SYSTEM_CONFIG.WORK_NOTES.MAX_MESSAGE_LENGTH,
      maxAttachmentsPerNote: SYSTEM_CONFIG.WORK_NOTES.MAX_ATTACHMENTS_PER_NOTE,
      enableReactions: SYSTEM_CONFIG.WORK_NOTES.ENABLE_REACTIONS,
      enableMentions: SYSTEM_CONFIG.WORK_NOTES.ENABLE_MENTIONS,
    },
    features: SYSTEM_CONFIG.FEATURES,
    ui: SYSTEM_CONFIG.UI
  };

  // Get configuration from database first (always try to read from DB)
  const { getConfigValue } = require('../services/configReader.service');
  
  // Get AI configuration from admin settings (database)
  const aiEnabled = (await getConfigValue('AI_ENABLED', 'true'))?.toLowerCase() === 'true';
  const remarkGenerationEnabled = (await getConfigValue('AI_REMARK_GENERATION_ENABLED', 'true'))?.toLowerCase() === 'true';
  const maxRemarkLength = parseInt(await getConfigValue('AI_MAX_REMARK_LENGTH', '2000') || '2000', 10);
  
  // Try to get AI service status (gracefully handle if not available)
  try {
    const { aiService } = require('../services/ai.service');
    
    return {
      ...baseConfig,
      ai: {
        enabled: aiEnabled && aiService.isAvailable(),
        provider: aiService.getProviderName(),
        remarkGenerationEnabled: remarkGenerationEnabled && aiEnabled && aiService.isAvailable(),
        maxRemarkLength: maxRemarkLength,
        features: {
          conclusionGeneration: remarkGenerationEnabled && aiEnabled && aiService.isAvailable()
        }
      }
    };
  } catch (error) {
    // AI service not available - return config with database values but AI disabled
    return {
      ...baseConfig,
      ai: {
        enabled: false,
        provider: 'None',
        remarkGenerationEnabled: false,
        maxRemarkLength: maxRemarkLength, // Use database value, not hardcoded
        features: {
          conclusionGeneration: false
        }
      }
    };
  }
}

/**
 * Log system configuration on startup
 */
export function logSystemConfig(): void {
  // System config logging disabled - use environment variables to verify settings
}

export default SYSTEM_CONFIG;

