export type ExtractedLink = {
  type: "app.bsky.feed.post" | "app.sidetrail.trail" | "http";
  uri: string;
} | null;

export function extractLink(content: string): ExtractedLink {
  if (!content) return null;

  // at:// URIs first
  const atUriMatch = content.match(/at:\/\/[^\s]+/);
  if (atUriMatch) {
    const uri = atUriMatch[0];
    if (uri.includes("/app.sidetrail.trail/")) {
      return { type: "app.sidetrail.trail", uri };
    }
    if (uri.includes("/app.bsky.feed.post/")) {
      return { type: "app.bsky.feed.post", uri };
    }
    return { type: "http", uri };
  }

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

    const trailAtUri = parseTrailUrl(uri);
    if (trailAtUri) return { type: "app.sidetrail.trail", uri: trailAtUri };

    if (uri.includes("bsky.app") && uri.includes("/post/")) {
      return { type: "app.bsky.feed.post", uri };
    }

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

  return null;
}

function parseTrailUrl(url: string): string | null {
  if (
    !url.includes("sidetrail.app") &&
    !url.includes("127.0.0.1:3000") &&
    !url.includes("localhost:3000")
  ) {
    return null;
  }
  const match = url.match(/@([\w.-]+)\/trail\/([\w]+)/);
  if (!match) return null;
  return `at://${match[1]}/app.sidetrail.trail/${match[2]}`;
}

export function hasLink(content: string): boolean {
  return extractLink(content) !== null;
}
