/**
 * Copyright 2024 Phenix Real Time Solutions, Inc. Confidential and Proprietary. All Rights Reserved.
 */

export type UrlType = 'pcast' | 'telemetry' | 'websocket';

export default class UrlService {
  public static getBaseUrlOrigin(url: string = window?.location?.href, urlType: UrlType = 'pcast'): string {
    if (!url) {
      throw new Error('Invalid URL');
    }

    const baseURL = new URL(url);
    const searchParams = new URLSearchParams(baseURL.search);
    const backendUrlParam = searchParams.get('backend');

    if (backendUrlParam) {
      return backendUrlParam;
    }

    const segments = baseURL.hostname.split('.');
    const prefix = urlType === 'telemetry' ? 'telemetry' : 'pcast';

    // Normalize WebSocket protocols to HTTP
    switch (baseURL.protocol) {
      case 'ws:':
        baseURL.protocol = 'http:';
        break;
      case 'wss:':
        baseURL.protocol = 'https:';
        break;
      default:
        break;
    }

    // Apply routing logic based on URL structure
    if (segments.length === 2 || (segments.length === 3 && segments[segments.length - 2].length <= 2 && segments[segments.length - 1].length <= 3)) {
      segments.unshift(prefix);
    } else if (segments[0].startsWith('stg-') || segments[0].endsWith('-stg') || segments[0].includes('-stg-') || segments[0] === 'stg') {
      segments[0] = `${prefix}-stg`;
    } else if (segments[0].startsWith('local') || segments[0].endsWith('-local')) {
      // Leave URL unchanged for local development
    } else {
      segments[0] = prefix;
    }

    baseURL.hostname = segments.join('.');

    return baseURL.origin;
  }

  public static getPcastBaseUrlOrigin(url: string = window?.location?.href): string {
    return this.getBaseUrlOrigin(url, 'pcast');
  }

  public static getTelemetryUrl(url: string = window?.location?.href): string {
    try {
      const baseUrlOrigin = this.getBaseUrlOrigin(url, 'telemetry');
      return `${baseUrlOrigin}/telemetry`;
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (e) {
      return url;
    }
  }

  public static getWebSocketUrl(url: string = window?.location?.href): string {
    const baseUrl = new URL(this.getBaseUrlOrigin(url, 'pcast'));
    baseUrl.protocol = 'wss:';
    baseUrl.pathname = '/ws';

    return baseUrl.toString();
  }
}
