// Link extraction utilities for trail stop content

export type ExtractedLink = { type: "bluesky"; uri: string } | { type: "http"; url: string } | null;

/**
 * Extracts the first link from text content.
 * Supports:
 * - at:// URIs (Bluesky/ATProto)
 * - http:// and https:// URLs (including bsky.app URLs)
 *
 * Returns the first link found, prioritizing at:// URIs.
 */
export function extractLink(content: string): ExtractedLink {
  if (!content) return null;

  // First, look for at:// URIs
  const atUriMatch = content.match(/at:\/\/[^\s]+/);
  if (atUriMatch) {
    const uri = atUriMatch[0];
    // It's a bluesky post
    return {
      type: "bluesky",
      uri: uri,
    };
  }

  // Then look for http(s):// URLs
  const httpMatch = content.match(/https?:\/\/[^\s]+/);
  if (httpMatch) {
    const url = httpMatch[0];

    // Check if it's a bsky.app URL
    if (url.includes("bsky.app")) {
      return {
        type: "bluesky",
        uri: url,
      };
    }

    return {
      type: "http",
      url: url,
    };
  }

  return null;
}

/**
 * Removes the extracted link from the text content.
 * Useful for displaying text without the raw link.
 */
export function removeLink(content: string, link: ExtractedLink): string {
  if (!link) return content;

  let linkText = "";
  if (link.type === "bluesky") {
    linkText = link.uri;
  } else {
    linkText = link.url;
  }

  return content.replace(linkText, "").trim();
}

/**
 * Checks if content contains a link
 */
export function hasLink(content: string): boolean {
  return extractLink(content) !== null;
}
