/**
 * URL validation utilities for secure iframe embedding
 * Prevents URL injection attacks in monitoring dashboards
 */

/**
 * Validates that a URL is safe for iframe embedding
 * Only allows localhost URLs on specific whitelisted ports
 *
 * @param url - The URL to validate
 * @param allowedPorts - Array of permitted port numbers
 * @returns The validated URL string
 * @throws Error if URL is not safe
 */
export function validateIframeUrl(url: string, allowedPorts: number[]): string {
  try {
    const parsed = new URL(url);

    // Only allow localhost/127.0.0.1
    if (!['localhost', '127.0.0.1'].includes(parsed.hostname)) {
      throw new Error('Invalid hostname: only localhost allowed');
    }

    // Check port whitelist
    const port = parseInt(parsed.port, 10);
    if (!allowedPorts.includes(port)) {
      throw new Error(`Invalid port: ${port} not in whitelist`);
    }

    return url;
  } catch (error) {
    if (error instanceof TypeError) {
      throw new Error(`Invalid URL format: ${url}`);
    }
    throw error;
  }
}

/**
 * Safely constructs iframe URL for monitoring services
 * Always uses localhost to prevent DNS rebinding attacks
 *
 * @param service - The monitoring service name
 * @param port - The service port number
 * @param path - Optional path (e.g., '/d/application-overview')
 * @returns Validated iframe URL
 */
export function buildMonitoringUrl(
  _service: 'grafana' | 'alertmanager',
  port: number,
  path = ''
): string {
  // Always use localhost (never trust window.location)
  const baseUrl = `http://localhost:${port}`;
  const url = new URL(path, baseUrl);

  // Validate before returning
  const allowedPorts = [3005, 9093]; // Grafana, Alertmanager
  return validateIframeUrl(url.toString(), allowedPorts);
}
