/**
 * BE-129 — when a sign-in screen sends a visitor home.
 *
 * These exist because the rule shipped broken: «sign in with another account»
 * opened `/login` and was bounced straight back to the homepage. The cause was
 * not this rule but an unmount cleanup that cleared the intent — Strict Mode
 * is on by default under the App Router, so React mounts, runs effects, runs
 * the **cleanups**, and mounts again, and the intent died a moment after the
 * screen opened. The cleanup is gone; this pins what the rule itself answers.
 */
import assert from "node:assert/strict";
import { describe, test } from "node:test";

import { shouldRedirectWhenLoggedIn } from "@/components/shared/authRedirect";

const decide = (overrides: Partial<Parameters<typeof shouldRedirectWhenLoggedIn>[0]> = {}) =>
  shouldRedirectWhenLoggedIn({
    sessionReady: true,
    signedIn: false,
    addingAccount: false,
    ...overrides,
  });

describe("shouldRedirectWhenLoggedIn", () => {
  test("a signed-out visitor keeps the form", () => {
    assert.equal(decide(), false);
  });

  test("a signed-in visitor is sent home", () => {
    assert.equal(decide({ signedIn: true }), true);
  });

  /* The whole point of the intent: a signed-in reader who came here on
     purpose, to add a second account, must reach the form. */
  test("adding an account keeps the form, even while signed in", () => {
    assert.equal(decide({ signedIn: true, addingAccount: true }), false);
  });

  /*
   * "Not known yet" is a third state, not a synonym for signed out. Acting on
   * it would bounce a signed-out visitor off the form they asked for — the
   * mirror of the defect `useSessionReady` was added for on the other guard,
   * where a signed-in reader was sent to `/login` on every reload.
   */
  test("nothing happens until the session is known", () => {
    assert.equal(decide({ sessionReady: false, signedIn: true }), false);
    assert.equal(decide({ sessionReady: false, signedIn: false }), false);
    assert.equal(
      decide({ sessionReady: false, signedIn: true, addingAccount: true }),
      false
    );
  });

  /* An intent with nobody signed in is meaningless but harmless: there is
     nothing to redirect away from. */
  test("the intent alone changes nothing", () => {
    assert.equal(decide({ addingAccount: true }), false);
  });
});
