import { type PublishCapability, type PublishIntent, canPublish } from "@/lib/publishPermissions";
import type { User } from "@/store/authStore";

export type RouteUserType = "volunteer" | "organization";

export interface RouteAccessRequest {
  user: User | null;
  userType?: RouteUserType | RouteUserType[];
  publish?: PublishCapability | PublishCapability[];
  publishIntent?: PublishIntent;
}

/**
 * Where this reader should be, given the route's requirements.
 *
 * `null` means "here" — render the screen. Anything else is the path to
 * replace the current entry with.
 */
export interface RouteAccess {
  allow: boolean;
  redirectTo: "/login" | "/" | null;
}

/**
 * `individual` is a frontend-only alias the guard collapses before comparing.
 *
 * The backend's `UserType` enum is `volunteer | organization | admin`; nothing
 * in the API produces `individual`, but `getPublisherKind` and this guard both
 * branch on it, so it stays in the union. **`admin` is deliberately not
 * collapsed**: no call site lists it, so an admin signing in to the public
 * site matches no guarded route and is sent home. The admin tooling is a
 * separate surface.
 */
export function effectiveUserType(user: User): string {
  return user.user_type === "individual" ? "volunteer" : user.user_type;
}

/**
 * The access decision for a guarded route, as a pure function.
 *
 * Extracted from `ProtectedRoute`, where it was written out **twice** — once
 * in the effect that redirects and once in the render that withholds the
 * children. Two copies of an access-control rule is one copy too many: they
 * could diverge into a screen that renders while the redirect is in flight, or
 * a redirect that fires for a reader who is then shown the page anyway.
 *
 * It is also a `.ts` module rather than logic inside the `.tsx` component
 * because that is what makes it testable here — Node's type stripping runs
 * `.ts` and not `.tsx`, so a decision table living in the component could not
 * be exercised at all. See `tests/routeGuards.test.ts`.
 *
 * The order matters and is the order the component used: authentication first,
 * then role, then publish capability. A signed-out reader goes to `/login`; a
 * signed-in reader who simply may not be here goes to `/` — sending them to
 * `/login` would be wrong, and `RedirectIfLoggedIn` would bounce them straight
 * back out of it.
 */
export function routeAccess({
  user,
  userType,
  publish,
  publishIntent,
}: RouteAccessRequest): RouteAccess {
  if (!user) return { allow: false, redirectTo: "/login" };

  if (userType) {
    const allowed = Array.isArray(userType) ? userType : [userType];
    if (!allowed.includes(effectiveUserType(user) as RouteUserType)) {
      return { allow: false, redirectTo: "/" };
    }
  }

  /* `canPublish` covers approval status and bans as well as the publisher
     kind: a pending, rejected or banned organization used to reach every
     publish form by typing the URL. */
  if (publish && !canPublish(user, publish, publishIntent)) {
    return { allow: false, redirectTo: "/" };
  }

  return { allow: true, redirectTo: null };
}
