export interface ParsedInviteQuery {
  inviteId: string;
  sourceUrl?: string;
}

/**
 * Parses a dashboard search query into invite context when it looks like an invite
 * code or URL. Returns `null` when the query is not invite-like.
 *
 * Accepted shapes:
 * - A bare code: `abc123`, `Team-Code_9` (6+ url-safe chars, no whitespace)
 * - A path or URL containing `/invite/<id>`
 * - Browser invite URLs with `?server=<signal-origin>`
 * - Signal-server invite URLs where the origin is the signal server
 * - `toju://invite/<id>?server=<signal-origin>`
 */
export function parseInviteQuery(rawQuery: string): ParsedInviteQuery | null {
  const query = rawQuery.trim();

  if (query.length === 0) {
    return null;
  }

  if (query.startsWith('toju:')) {
    const protocolInvite = parseTojuInviteUrl(query);

    if (protocolInvite) {
      return protocolInvite;
    }
  }

  const invitePathMatch = /\/invite\/([A-Za-z0-9_-]+)/.exec(query);

  if (invitePathMatch) {
    return {
      inviteId: invitePathMatch[1],
      sourceUrl: deriveSourceUrlFromInviteReference(query)
    };
  }

  if (/^[A-Za-z0-9_-]{6,}$/.test(query)) {
    return { inviteId: query };
  }

  return null;
}

function parseTojuInviteUrl(url: string): ParsedInviteQuery | null {
  try {
    const parsedUrl = new URL(url);
    const pathSegments = [parsedUrl.hostname, ...parsedUrl.pathname.split('/').filter(Boolean)]
      .map((segment) => decodeURIComponent(segment));

    if (pathSegments[0] !== 'invite' || !pathSegments[1]) {
      return null;
    }

    return {
      inviteId: pathSegments[1],
      sourceUrl: parsedUrl.searchParams.get('server')?.trim() || undefined
    };
  } catch {
    return null;
  }
}

function deriveSourceUrlFromInviteReference(reference: string): string | undefined {
  try {
    const normalizedReference = reference.includes('://')
      ? reference
      : `https://placeholder.test${reference.startsWith('/') ? reference : `/${reference}`}`;
    const parsed = new URL(normalizedReference);
    const serverParam = parsed.searchParams.get('server')?.trim();

    if (serverParam) {
      return serverParam;
    }

    if (parsed.hostname === 'placeholder.test') {
      return undefined;
    }

    if (isLikelySignalServerOrigin(parsed)) {
      return `${parsed.protocol}//${parsed.host}`;
    }

    return undefined;
  } catch {
    return undefined;
  }
}

function isLikelySignalServerOrigin(url: URL): boolean {
  return url.hostname.startsWith('signal.') || url.port === '3001';
}

