/**
 * Enterprise Configuration
 * 
 * Centralized configuration management with Zod validation.
 * All environment variables validated at startup.
 */

import dotenv from 'dotenv';
import { z } from 'zod';

// Load environment variables
dotenv.config();

/**
 * Environment schema with strict validation
 */
const envSchema = z.object({
  // Server
  NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
  PORT: z.string().transform(Number).pipe(z.number().int().positive()).default('3001'),
  HOST: z.string().default('0.0.0.0'),
  
  // Database
  DATABASE_URL: z.string().url().min(1, 'DATABASE_URL is required'),
  
  // Redis
  REDIS_URL: z.string().url().optional(),
  
  // Security
  JWT_SECRET: z.string().min(32, 'JWT_SECRET must be at least 32 characters'),
  JWT_EXPIRES_IN: z.string().default('15m'),
  
  // AI
  AI_API_KEY: z.string().min(1, 'AI_API_KEY is required'),
  AI_MODEL: z.string().default('MiniMax-M2.5'),
  AI_MAX_TOKENS: z.string().transform(Number).pipe(z.number().int().positive()).default('1024'),
  AI_TEMPERATURE: z.string().transform(Number).pipe(z.number().min(0).max(2)).default('0.7'),
  AI_TIMEOUT_MS: z.string().transform(Number).pipe(z.number().int().positive()).default('30000'),
  
  // Telegram
  TELEGRAM_BOT_TOKEN: z.string().optional(),
  TELEGRAM_ADMIN_CHAT_ID: z.string().optional(),
  
  // Frontend
  FRONTEND_URL: z.string().url().default('http://localhost:3000'),
  CORS_ORIGIN: z.string().default('http://localhost:3000'),
  
  // Rate Limiting
  RATE_LIMIT_WINDOW_MS: z.string().transform(Number).pipe(z.number().int().positive()).default('900000'),
  RATE_LIMIT_MAX_REQUESTS: z.string().transform(Number).pipe(z.number().int().positive()).default('100'),
  
  // Logging
  LOG_LEVEL: z.enum(['error', 'warn', 'info', 'http', 'debug', 'verbose']).default('info'),
  LOG_FILE_PATH: z.string().default('./logs'),
  
  // Uploads
  MAX_FILE_SIZE_MB: z.string().transform(Number).pipe(z.number().int().positive()).default('10'),
  ALLOWED_FILE_TYPES: z.string().default('image/jpeg,image/png,application/pdf'),
});

/**
 * Parse environment variables
 */
const parsedEnv = envSchema.safeParse(process.env);

if (!parsedEnv.success) {
  console.error('❌ Invalid environment variables:');
  parsedEnv.error.issues.forEach((issue) => {
    console.error(`  - ${issue.path.join('.')}: ${issue.message}`);
  });
  process.exit(1);
}

/**
 * Validated configuration object
 */
export const config = {
  ...parsedEnv.data,
  
  // Computed properties
  isDevelopment: parsedEnv.data.NODE_ENV === 'development',
  isProduction: parsedEnv.data.NODE_ENV === 'production',
  isTest: parsedEnv.data.NODE_ENV === 'test',
  
  // Timeouts
  defaultTimeout: 30000,
  dbConnectionTimeout: 10000,
  cacheDefaultTTL: 300,
  
  // Limits
  maxRequestBodySize: '10mb',
  maxFileUploadSize: parsedEnv.data.MAX_FILE_SIZE_MB * 1024 * 1024,
  
  // Pagination
  defaultPageSize: 20,
  maxPageSize: 100,
  
  // Token expiration (in seconds)
  accessTokenExpirySeconds: 900, // 15 minutes
  refreshTokenExpiryDays: 7,
} as const;

/**
 * Type of the configuration
 */
export type Config = typeof config;

export default config;
