import type { ServerEndpoint } from '../models/server-directory.model';
import { sanitiseServerBaseUrl } from './server-endpoint-defaults.logic';

export type SignalServerTagPresentation =
  | { kind: 'url'; url: string }
  | { kind: 'label'; label: string; display: string };

export function isSignalServerTagUrl(value: string): boolean {
  return /^https?:\/\//i.test(value.trim());
}

export function presentSignalServerTag(tag: string): SignalServerTagPresentation {
  const normalized = tag.trim();

  if (isSignalServerTagUrl(normalized)) {
    return { kind: 'url', url: normalized };
  }

  const label = normalized.replace(/^#+/, '');

  return { kind: 'label', label, display: `#${label}` };
}

export function resolveEndpointSignalServerTag(
  endpoint: Pick<ServerEndpoint, 'serverTag' | 'url'>
): string {
  const configuredTag = endpoint.serverTag?.trim();

  return configuredTag || endpoint.url;
}

export function resolveUserHomeSignalServerTag(
  homeSignalServerUrl: string | undefined,
  endpoints: ServerEndpoint[]
): string | undefined {
  const normalizedHomeUrl = homeSignalServerUrl?.trim();

  if (!normalizedHomeUrl) {
    return undefined;
  }

  const sanitizedHomeUrl = sanitiseServerBaseUrl(normalizedHomeUrl);
  const matchingEndpoint = endpoints.find(
    (endpoint) => sanitiseServerBaseUrl(endpoint.url) === sanitizedHomeUrl
  );

  if (matchingEndpoint) {
    return resolveEndpointSignalServerTag(matchingEndpoint);
  }

  return sanitizedHomeUrl;
}
