/**
 * WebSocket Route Helper Functions
 *
 * This module provides utility functions for creating WebSocket route configurations.
 */

import type { IRouteConfig, IRouteMatch, IRouteAction } from '../../models/route-types.js';

/**
 * Create a WebSocket route configuration
 * @param domains Domain(s) to match
 * @param targetOrPath Target server OR WebSocket path (legacy)
 * @param targetOrOptions Target server (legacy) OR options
 * @param options Additional route options (legacy)
 * @returns Route configuration object
 */
export function createWebSocketRoute(
  domains: string | string[],
  targetOrPath: { host: string | string[]; port: number } | string,
  targetOrOptions?: { host: string | string[]; port: number } | {
    useTls?: boolean;
    certificate?: 'auto' | { key: string; cert: string };
    path?: string;
    httpPort?: number | number[];
    httpsPort?: number | number[];
    pingInterval?: number;
    pingTimeout?: number;
    name?: string;
    [key: string]: any;
  },
  options?: {
    useTls?: boolean;
    certificate?: 'auto' | { key: string; cert: string };
    httpPort?: number | number[];
    httpsPort?: number | number[];
    pingInterval?: number;
    pingTimeout?: number;
    name?: string;
    [key: string]: any;
  }
): IRouteConfig {
  // Handle different signatures
  let target: { host: string | string[]; port: number };
  let wsPath: string;
  let finalOptions: any;

  if (typeof targetOrPath === 'string') {
    // Legacy signature: (domains, path, target, options)
    wsPath = targetOrPath;
    target = targetOrOptions as { host: string | string[]; port: number };
    finalOptions = options || {};
  } else {
    // New signature: (domains, target, options)
    target = targetOrPath;
    finalOptions = (targetOrOptions as any) || {};
    wsPath = finalOptions.path || '/ws';
  }

  // Normalize WebSocket path
  const normalizedPath = wsPath.startsWith('/') ? wsPath : `/${wsPath}`;

  // Create route match
  const match: IRouteMatch = {
    ports: finalOptions.useTls
      ? (finalOptions.httpsPort || 443)
      : (finalOptions.httpPort || 80),
    domains,
    path: normalizedPath
  };

  // Create route action
  const action: IRouteAction = {
    type: 'forward',
    targets: [target],
    websocket: {
      enabled: true,
      pingInterval: finalOptions.pingInterval || 30000, // 30 seconds
      pingTimeout: finalOptions.pingTimeout || 5000    // 5 seconds
    }
  };

  // Add TLS configuration if using HTTPS
  if (finalOptions.useTls) {
    action.tls = {
      mode: 'terminate',
      certificate: finalOptions.certificate || 'auto'
    };
  }

  // Create the route config
  return {
    match,
    action,
    name: finalOptions.name || `WebSocket Route ${normalizedPath} for ${Array.isArray(domains) ? domains.join(', ') : domains}`,
    priority: finalOptions.priority || 100, // Higher priority for WebSocket routes
    ...finalOptions
  };
}
