---
import type { HTMLAttributes } from "astro/types";
import { $path, type RouteOptions } from "astro-js-typesafe-routes/path";

type LinkBase = Omit<HTMLAttributes<"a">, "href">;

type InternalProps = LinkBase &
  RouteOptions & {
    external?: false;
    href?: never;
  };

type ExternalProps = LinkBase & {
  external: true;
  href: string;
  to?: never;
};

export type Props = InternalProps | ExternalProps;

const { external = false, ...props } = Astro.props;

let resolvedHref: string;
let anchorProps: Record<string, any>;

if (external) {
  const { href: rawHref, ...rest } = props as unknown as ExternalProps;
  resolvedHref = rawHref;
  anchorProps = rest;
} else {
  const { to, params, locale, search, hash, ...rest } =
    props as unknown as InternalProps;
  resolvedHref = $path({ to, params, locale, search, hash });
  anchorProps = rest;
}
---

<a href={resolvedHref} {...anchorProps}><slot /></a>
