// AUTO-GENERATED by `wrnexus dev` - do not edit.
// Typed routes support required, optional, and catch-all parameters.

export interface Routes {
  "/": Record<string, never>;
  "/captcha": Record<string, never>;
  "/protected": Record<string, never>;
  "/styles": Record<string, never>;
}

export type RoutePath = keyof Routes;
type RouteValue = string | readonly string[] | undefined;

function encodeRouteValue(value: RouteValue, catchAll: boolean): string {
  if (value === undefined) return "";
  const values = Array.isArray(value) ? value : catchAll ? String(value).split("/") : [String(value)];
  return values.map((part) => encodeURIComponent(part)).join("/");
}

export function href<P extends RoutePath>(
  path: P,
  ...args: keyof Routes[P] extends never
    ? []
    : Record<string, never> extends Routes[P]
      ? [params?: Routes[P]]
      : [params: Routes[P]]
): string {
  const params = (args[0] ?? {}) as Record<string, RouteValue>;
  const output: string[] = [];
  for (const segment of String(path).split("/").filter(Boolean)) {
    let name: string | undefined;
    let optional = false;
    let catchAll = false;
    if (segment.startsWith("[[") && segment.endsWith("]]")) {
      optional = true;
      name = segment.slice(2, -2);
    } else if (segment.startsWith("[") && segment.endsWith("]")) {
      name = segment.slice(1, -1);
      if (name.endsWith("?")) {
        optional = true;
        name = name.slice(0, -1);
      }
    }
    if (!name) {
      output.push(segment);
      continue;
    }
    if (name.startsWith("...")) {
      catchAll = true;
      name = name.slice(3);
    }
    const value = params[name];
    if (value === undefined && optional) continue;
    if (value === undefined) throw new Error(`WRN-ROUTE-MISSING-PARAM: Missing route parameter '${name}'.`);
    output.push(encodeRouteValue(value, catchAll));
  }
  return "/" + output.filter(Boolean).join("/");
}
