"use client";

// Routes that have been renamed, and where they went.
//
// Single source of truth, consumed by three places that must never disagree:
//
//   src/app/not-found.tsx    redirects a client-side navigation that lands here
//   src/hooks/useRouteTracker.ts   refuses to record these as destinations
//   public/.htaccess         redirects a hard navigation (server side)
//
// A retired route is NOT a destination. It is a waypoint that always sends the
// user somewhere else, and anything that treats it as a place the user "was"
// will trap them:
//
//   stack: [..., /course/detail?id=45, /course/view?id=45, /course/detail?id=45]
//
// Back pops /course/detail, lands on /course/view, which redirects forward to
// /course/detail, which the route tracker then records again -- reproducing
// the stack it started from. The back button can never shrink it, and the user
// is stuck bouncing between two screens forever. That was a real bug, and it
// only appeared once the redirect existed: while /course/view was a dead-end
// 404 there was nothing to bounce off.
//
// Add to this map on every rename. Keys are pathnames with no trailing slash
// and no query.
export const RETIRED_ROUTES: Record<string, string> = {
    "/course/view": "/course/detail",
};

/** Strips a trailing slash so "/course/view/" and "/course/view" are one key. */
export function normalizePath(pathname: string): string {
    return pathname.replace(/\/+$/, "") || "/";
}

/** Where a retired path went, or null if the path is a real destination. */
export function retiredTarget(pathname: string): string | null {
    return RETIRED_ROUTES[normalizePath(pathname)] ?? null;
}

/** True if this path always redirects, and so is never somewhere the user is. */
export function isRetiredRoute(pathname: string): boolean {
    return retiredTarget(pathname) !== null;
}

/**
 * Where a path actually lands, following one retirement hop.
 *
 * Used to compare history entries by their real destination: an entry for
 * /course/view and an entry for /course/detail are the same screen, and
 * treating them as different is what created the loop.
 */
export function resolvePath(pathname: string): string {
    return retiredTarget(pathname) ?? normalizePath(pathname);
}
