"use client";

import NextLink, { type LinkProps } from "next/link";
import { forwardRef } from "react";
import { withBuildIdUrl } from "@/lib/update";
import { isInternalPath } from "@/lib/update/identity";

// Drop-in replacement for next/link's <Link>.
type VersionedLinkProps = Omit<LinkProps, "href"> &
    Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, keyof LinkProps> & {
        href: LinkProps["href"];
    };

function isInternalHref(href: LinkProps["href"]): boolean {
    if (typeof href === "string") return isInternalPath(href);
    return !!href.pathname && isInternalPath(href.pathname);
}

const VersionedLink = forwardRef<HTMLAnchorElement, VersionedLinkProps>(
    function VersionedLink({ href, target, ...rest }, ref) {
        // No tabs in the apps: keep internal links in the app (external ones open the browser).
        const keepInApp =
            process.env.NEXT_PUBLIC_APP_TARGET === "native" &&
            target === "_blank" &&
            isInternalHref(href);

        return (
            <NextLink
                ref={ref}
                href={withBuildIdUrl(href)}
                target={keepInApp ? undefined : target}
                {...rest}
            />
        );
    }
);

export default VersionedLink;
