/**
 * Security Configuration
 *
 * Implements OWASP Top 10 security best practices
 */

import { HelmetOptions } from 'helmet';

export const helmetConfig: HelmetOptions = {
  // Content Security Policy
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"], // Required for inline styles in some frameworks
      scriptSrc: ["'self'"],
      imgSrc: ["'self'", 'data:', 'https:'],
      connectSrc: ["'self'"],
      fontSrc: ["'self'"],
      objectSrc: ["'none'"],
      mediaSrc: ["'self'"],
      frameSrc: ["'none'"],
    },
  },

  // Cross-Origin Embedder Policy
  crossOriginEmbedderPolicy: false, // Set to true in production if needed

  // Cross-Origin Opener Policy
  crossOriginOpenerPolicy: { policy: 'same-origin' },

  // Cross-Origin Resource Policy
  crossOriginResourcePolicy: { policy: 'same-origin' },

  // DNS Prefetch Control
  dnsPrefetchControl: { allow: false },

  // Frameguard
  frameguard: { action: 'deny' },

  // Hide Powered-By
  hidePoweredBy: true,

  // HSTS (HTTP Strict Transport Security)
  hsts: {
    maxAge: 31536000, // 1 year
    includeSubDomains: true,
    preload: true,
  },

  // IE No Open
  ieNoOpen: true,

  // No Sniff
  noSniff: true,

  // Origin Agent Cluster
  originAgentCluster: true,

  // Permitted Cross-Domain Policies
  permittedCrossDomainPolicies: { permittedPolicies: 'none' },

  // Referrer Policy
  referrerPolicy: { policy: 'no-referrer' },

  // XSS Filter
  xssFilter: true,
};

/**
 * Rate Limiting Configuration
 */
export const rateLimitConfig = {
  // Global rate limit
  global: {
    ttl: 60, // 60 seconds
    limit: 100, // 100 requests per minute
  },

  // Auth endpoints (more strict)
  auth: {
    ttl: 60,
    limit: 5, // 5 login attempts per minute
  },

  // Search endpoints
  search: {
    ttl: 60,
    limit: 30, // 30 searches per minute
  },

  // Booking endpoints
  booking: {
    ttl: 60,
    limit: 20, // 20 bookings per minute
  },
};

/**
 * CORS Configuration
 */
export const corsConfig = {
  origin: process.env.FRONTEND_URL || ['http://localhost:3000', 'http://localhost:3001'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
  exposedHeaders: ['X-Total-Count', 'X-Page-Count'],
  maxAge: 86400, // 24 hours
};

/**
 * Session Configuration
 */
export const sessionConfig = {
  secret: process.env.SESSION_SECRET || 'change-this-secret',
  resave: false,
  saveUninitialized: false,
  cookie: {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production', // HTTPS only in production
    sameSite: 'strict' as const,
    maxAge: 7200000, // 2 hours
  },
};

/**
 * Password Policy
 */
export const passwordPolicy = {
  minLength: 12,
  requireUppercase: true,
  requireLowercase: true,
  requireNumbers: true,
  requireSymbols: true,
  maxLength: 128,
  preventCommon: true, // Prevent common passwords
  preventReuse: 5, // Last 5 passwords
};

/**
 * File Upload Configuration
 */
export const fileUploadConfig = {
  maxFileSize: 10 * 1024 * 1024, // 10MB
  allowedMimeTypes: [
    'application/pdf',
    'image/jpeg',
    'image/png',
    'image/webp',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'text/csv',
  ],
  allowedExtensions: ['.pdf', '.jpg', '.jpeg', '.png', '.webp', '.xls', '.xlsx', '.csv'],
  scanForViruses: process.env.NODE_ENV === 'production',
};

/**
 * JWT Configuration
 */
export const jwtConfig = {
  accessToken: {
    secret: process.env.JWT_SECRET || 'change-this-secret',
    expiresIn: '15m', // 15 minutes
  },
  refreshToken: {
    secret: process.env.JWT_REFRESH_SECRET || 'change-this-refresh-secret',
    expiresIn: '7d', // 7 days
  },
  algorithm: 'HS256' as const,
};

/**
 * Brute Force Protection
 */
export const bruteForceConfig = {
  freeRetries: 3,
  minWait: 5 * 60 * 1000, // 5 minutes
  maxWait: 60 * 60 * 1000, // 1 hour
  lifetime: 24 * 60 * 60, // 24 hours
};
