/**
 * The route-guard access decision, and the rehydration timing it depends on.
 *
 * `ProtectedRoute` decides who reaches sixteen screens and had no tests at
 * all. It is also where a mistake is silent: a guard that renders its children
 * one frame too early shows a signed-out visitor a screen it should not, and
 * one that redirects too eagerly throws a signed-in visitor back to `/login`
 * on every reload. Neither shows up in a type check or in lint.
 *
 * The decision is now `routeAccess`, a pure function, which is what is
 * exercised here. Two limits, stated rather than papered over:
 *
 *  - **The components themselves cannot be mounted in this suite.** Node's
 *    type stripping runs `.ts` and not `.tsx`, so `ProtectedRoute.tsx` and
 *    `RedirectIfLoggedIn.tsx` are not importable by the test runner. That is
 *    the reason the decision was extracted into a `.ts` module, and it is why
 *    these tests assert *what the guard decides*, not that `router.replace`
 *    was called with it.
 *  - **Whether the redirect then navigates needs a browser.** So does what the
 *    reader sees while it is in flight.
 */
import { beforeEach, describe, test } from "node:test";
import assert from "node:assert/strict";
import { pathToFileURL } from "node:url";
import { join } from "node:path";

import { installDom, renderHook } from "./reactHarness";
import {
  effectiveUserType,
  routeAccess,
  type RouteUserType,
} from "@/components/shared/routeAccess";
import type { User } from "@/store/authStore";

const baseUser: User = {
  id: 1,
  first_name: "A",
  last_name: "B",
  email: "a@b.test",
  profile_pic: null,
  social_media_id: null,
  social_media_provider: null,
  user_type: "volunteer",
  manual_id: null,
  is_new_user: false,
  is_verified: true,
  auth_token: "token",
};

const asUser = (over: Partial<User> = {}): User => ({ ...baseUser, ...over });
const BOTH: RouteUserType[] = ["volunteer", "organization"];

describe("unauthenticated access", () => {
  test("withheld, and sent to /login", () => {
    assert.deepEqual(routeAccess({ user: null, userType: BOTH }), {
      allow: false,
      redirectTo: "/login",
    });
  });

  test("withheld even when the route states no role requirement", () => {
    /* A route with no `userType` still requires a session — the prop narrows
       *which* signed-in readers may enter, it does not make the route open. */
    assert.deepEqual(routeAccess({ user: null }), {
      allow: false,
      redirectTo: "/login",
    });
  });
});

describe("role restrictions", () => {
  test("the matching type is admitted", () => {
    assert.deepEqual(routeAccess({ user: asUser(), userType: "volunteer" }), {
      allow: true,
      redirectTo: null,
    });
  });

  test("the wrong type goes to / rather than /login", () => {
    /* Deliberate: they *are* signed in, so `/login` would be wrong — and
       `RedirectIfLoggedIn` wraps that route, so it would bounce them straight
       back out and the reader would end up somewhere arbitrary. */
    assert.deepEqual(
      routeAccess({ user: asUser({ user_type: "organization" }), userType: "volunteer" }),
      { allow: false, redirectTo: "/" }
    );
  });

  test("individual is admitted wherever volunteer is", () => {
    assert.equal(effectiveUserType(asUser({ user_type: "individual" })), "volunteer");
    assert.equal(
      routeAccess({ user: asUser({ user_type: "individual" }), userType: "volunteer" })
        .allow,
      true
    );
  });

  test("admin matches no guard and is sent to /", () => {
    /* `admin` is a real backend `user_type` and no call site lists it, so an
       admin signing in to the public site reaches none of the guarded routes.
       Pinned because it reads like an oversight and is not — the admin tooling
       is a separate surface — so a future "fix" should be a decision, not a
       tidy-up. */
    assert.equal(effectiveUserType(asUser({ user_type: "admin" })), "admin");
    for (const userType of [["volunteer"], ["organization"], BOTH] as RouteUserType[][]) {
      assert.deepEqual(
        routeAccess({ user: asUser({ user_type: "admin" }), userType }),
        { allow: false, redirectTo: "/" }
      );
    }
  });

  test("a route listing both types admits both", () => {
    for (const user_type of ["volunteer", "organization", "individual"] as const) {
      assert.equal(
        routeAccess({ user: asUser({ user_type }), userType: BOTH }).allow,
        true,
        user_type
      );
    }
  });
});

describe("publish capability", () => {
  /*
   * **Approval is `is_verified`, not `organization.organization_status`.**
   *
   * The two look independent — `CLAUDE.md` describes `organization_status` as
   * gating org-only actions "independently of the login state" — and they are
   * not. `WebsiteLoginUserResource::isVerified()` returns
   * `organizationProfile->isApproved()` for an organization account, so
   * `is_verified` *is* `organization_status === 'approved'`, already computed
   * server-side, and it is the same condition `PublishPolicy::allows()` calls
   * `$isApprovedOrg`.
   *
   * So the frontend reads the right field. This is pinned because the first
   * draft of these tests set `organization_status` and left `is_verified`
   * alone, built a payload the API cannot produce, and read as a permission
   * hole.
   */
  const org = (over: Partial<User> = {}) =>
    asUser({
      user_type: "organization",
      is_verified: true,
      organization: { id: 9, organization_status: "approved" },
      organizer_type_display: { value_en: "Commercial" },
      ...over,
    });

  /** An unapproved organization, in the shape the API actually sends. */
  const unapprovedOrg = (status: "pending" | "rejected") =>
    org({ is_verified: false, organization: { id: 9, organization_status: status } });

  test("an approved organization reaches a publish form", () => {
    assert.deepEqual(
      routeAccess({ user: org(), userType: "organization", publish: "events" }),
      { allow: true, redirectTo: null }
    );
  });

  for (const status of ["pending", "rejected"] as const) {
    test(`a ${status} organization is refused`, () => {
      /* Before `publish` was checked in the guard, a pending, rejected or
         banned organization reached every publish form by typing the URL. */
      assert.deepEqual(
        routeAccess({
          user: unapprovedOrg(status),
          userType: "organization",
          publish: "events",
        }),
        { allow: false, redirectTo: "/" }
      );
    });
  }

  test("a ban overrides approval", () => {
    assert.equal(
      routeAccess({
        user: org({ is_banned: true }),
        userType: "organization",
        publish: "events",
      }).allow,
      false
    );
  });

  test("a volunteer is refused an organization publish form on the role check", () => {
    /* Both checks answer `/`, so the redirect is the same either way; the
       order is pinned because the reasons differ. */
    assert.deepEqual(
      routeAccess({
        user: asUser({ user_type: "volunteer" }),
        userType: "organization",
        publish: "events",
      }),
      { allow: false, redirectTo: "/" }
    );
  });

  test("an unapproved volunteer team is still refused events — in the UI and on the server", () => {
    /*
     * BE-108's other half. `getPublisherKind` cannot see a team today
     * (`organizer_type_display` is absent from the sign-in payload), so an
     * *approved* team is wrongly offered events here — that is the open
     * affordance bug, traced and filed, not worked around.
     *
     * What this pins is the part that does hold: approval is required first,
     * so an unapproved team is refused by the guard for the same reason the
     * server refuses it.
     */
    const team = asUser({
      user_type: "organization",
      is_verified: false,
      organizer_type_display: { value_en: "Volunteer Team" },
      organization: { id: 9, organization_status: "pending" },
    });
    assert.equal(
      routeAccess({ user: team, userType: "organization", publish: "events" }).allow,
      false
    );
  });

  test("an approved team is admitted to a volunteer form, which the server also allows", () => {
    const team = asUser({
      user_type: "organization",
      is_verified: true,
      organizer_type_display: { value_en: "Volunteer Team" },
      organization: { id: 9, organization_status: "approved" },
    });
    assert.equal(
      routeAccess({ user: team, userType: "organization", publish: "volunteer" }).allow,
      true
    );
  });
});

describe("reload behaviour — persisted session timing", () => {
  beforeEach(() => {
    installDom();
  });

  test("a persisted user is present on a fresh mount's first render", async () => {
    /*
     * **This covers a client-side navigation, not a reload.** On a fresh mount
     * there is no hydration render, so the first committed value is already
     * the real session: `persist` reads `localStorage` synchronously while the
     * store module is evaluated.
     *
     * An earlier revision of this test was titled "the guard's first render"
     * and used to carry a note saying this was why a signed-in visitor is not
     * bounced to `/login` on reload. That was wrong, and it is why
     * `tests/sessionHydration.test.ts` exists: on a **reload** React uses
     * `getInitialState()` for the hydration render, the guard's effect fires
     * once with no session, and the redirect did happen. `useSessionReady` is
     * what prevents it.
     */
    const local = new Map<string, string>();
    const storage = {
      getItem: (k: string) => local.get(k) ?? null,
      setItem: (k: string, v: string) => void local.set(k, v),
      removeItem: (k: string) => void local.delete(k),
      clear: () => local.clear(),
      key: () => null,
      get length() {
        return local.size;
      },
    } as Storage;
    for (const target of [globalThis, globalThis.window as unknown as object]) {
      Object.defineProperty(target, "localStorage", {
        value: storage,
        configurable: true,
      });
    }
    storage.setItem(
      "fursa-auth",
      JSON.stringify({ state: { user: asUser() }, version: 0 })
    );

    /* Imported after the storage is seeded: `persist` reads it during module
       evaluation, so the import *is* the rehydration. A cache-busting query on
       the file URL makes this independent of any earlier import in the suite —
       the `@/` alias resolver takes a bare path, not a query, so the URL is
       built here. */
    const storeUrl = pathToFileURL(
      join(import.meta.dirname, "..", "src", "store", "authStore.ts")
    );
    storeUrl.searchParams.set("reload", String(Date.now()));
    const { useAuthStore } = (await import(storeUrl.href)) as typeof import("@/store/authStore");

    const probe = renderHook(() =>
      routeAccess({ user: useAuthStore.getState().user, userType: "volunteer" })
    );
    probe.mount();

    assert.deepEqual(
      probe.renders[0],
      { allow: true, redirectTo: null },
      "a fresh mount's first render must already admit the reader"
    );
  });
});
