const REPO_PATH_RE =
  /(?:^|\s)(https?:\/\/[^\s/]+)\/([^\s/]+)\/repo\/([^\s/?&#]+)(\/[^\s]*)?(?=\s|$)/g;

export interface RepoLinkMatch {
  /** Full matched URL string */
  url: string;
  /** Domain (e.g. "https://gitdata.ai") */
  domain: string;
  /** Workspace / org name */
  workspace: string;
  /** Repo name */
  repo: string;
  /** Extra path after the repo name (e.g. "/code", "/issues") */
  rest: string;
}

/**
 * Parse repo links out of a text message.
 * Only matches links that share the same origin as the current page.
 */
export function parseRepoLinks(text: string): RepoLinkMatch[] {
  const currentOrigin = window.location.origin;
  const results: RepoLinkMatch[] = [];

  for (const match of text.matchAll(REPO_PATH_RE)) {
    const domain = match[1];
    if (domain !== currentOrigin) continue;
    results.push({
      url: match[0].trim(),
      domain,
      workspace: match[2],
      repo: match[3],
      rest: match[4] ?? "",
    });
  }

  return results;
}
