import { Request } from 'express';

function buildOrigin(protocol: string, host: string): string {
  return `${protocol}://${host}`.replace(/\/+$/, '');
}

function originFromUrl(url: URL): string {
  return buildOrigin(url.protocol.replace(':', ''), url.host);
}

export function getRequestOrigin(request: Request): string {
  const forwardedProtoHeader = request.get('x-forwarded-proto');
  const forwardedHostHeader = request.get('x-forwarded-host');
  const protocol = forwardedProtoHeader?.split(',')[0]?.trim() || request.protocol;
  const host = forwardedHostHeader?.split(',')[0]?.trim() || request.get('host') || 'localhost';

  return buildOrigin(protocol, host);
}

export function deriveWebAppOrigin(signalOrigin: string): string {
  const url = new URL(signalOrigin);

  if (url.hostname === 'signal.toju.app' && !url.port) {
    return 'https://web.toju.app';
  }

  if (url.hostname.startsWith('signal.')) {
    url.hostname = url.hostname.replace(/^signal\./, 'web.');

    if (url.port === '3001') {
      url.port = '4200';
    }

    return originFromUrl(url);
  }

  if (url.port === '3001') {
    url.port = '4200';
    return originFromUrl(url);
  }

  return 'https://web.toju.app';
}

export function buildInviteUrl(signalOrigin: string, inviteId: string): string {
  return `${signalOrigin.replace(/\/+$/, '')}/invite/${encodeURIComponent(inviteId)}`;
}

export function buildBrowserInviteUrl(signalOrigin: string, inviteId: string): string {
  const browserOrigin = deriveWebAppOrigin(signalOrigin);

  return `${browserOrigin.replace(/\/+$/, '')}/invite/${encodeURIComponent(inviteId)}?server=${encodeURIComponent(signalOrigin)}`;
}

export function buildAppInviteUrl(signalOrigin: string, inviteId: string): string {
  return `toju://invite/${encodeURIComponent(inviteId)}?server=${encodeURIComponent(signalOrigin)}`;
}
