/**
 * BE-129 — holding more than one session on a device.
 *
 * The backend scopes each login token independently (signing in as B does not
 * invalidate A), so which token to send is entirely a client decision. These
 * cover the decision, not the menu: the store's rules are where a mistake
 * would sign someone into the wrong account or quietly drop a session.
 */
import assert from "node:assert/strict";
import { beforeEach, describe, test } from "node:test";

import { useAuthStore, type User } from "@/store/authStore";
import { accountKindKey, accountLabel } from "@/features/auth/accountLabel";

const account = (id: number, overrides: Partial<User> = {}): User => ({
  id,
  first_name: `User${id}`,
  last_name: null,
  email: `user${id}@example.com`,
  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-${id}`,
  ...overrides,
});

const reset = () =>
  useAuthStore.setState({
    user: null,
    accounts: [],
    addingAccount: false,
    isActiveLogout: false,
    profilePicTimestamp: null,
  });

describe("authStore — several sessions", () => {
  beforeEach(reset);

  test("the first sign-in backgrounds nothing", () => {
    useAuthStore.getState().setUser(account(1));
    assert.equal(useAuthStore.getState().user?.id, 1);
    assert.deepEqual(useAuthStore.getState().accounts, []);
  });

  test("a second sign-in keeps the first, most recent first", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 2);
    assert.deepEqual(
      state.accounts.map((a) => a.id),
      [1]
    );
  });

  /* Signing in again as the active account is a refreshed token, not a second
     session — stacking it would leave a stale token in the list. */
  test("signing in again as the active account does not duplicate it", () => {
    useAuthStore.getState().setUser(account(1, { auth_token: "old" }));
    useAuthStore.getState().setUser(account(1, { auth_token: "new" }));
    const state = useAuthStore.getState();
    assert.equal(state.user?.auth_token, "new");
    assert.deepEqual(state.accounts, []);
  });

  /* And signing in as an account already in the background promotes it rather
     than leaving one id in two places — which is what would decide whose
     token the interceptor sends. */
  test("signing in as a backgrounded account leaves no copy behind", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().setUser(account(1, { auth_token: "fresh" }));
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 1);
    assert.equal(state.user?.auth_token, "fresh");
    assert.deepEqual(
      state.accounts.map((a) => a.id),
      [2]
    );
  });

  test("switching swaps the active session with a stored one", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().switchAccount(1);
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 1);
    assert.equal(state.user?.auth_token, "token-1");
    assert.deepEqual(
      state.accounts.map((a) => a.id),
      [2]
    );
  });

  test("switching to an id that is not there changes nothing", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().switchAccount(99);
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 1);
    assert.deepEqual(state.accounts, []);
  });

  test("switching back and forth does not grow the list", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().switchAccount(1);
    useAuthStore.getState().switchAccount(2);
    useAuthStore.getState().switchAccount(1);
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 1);
    assert.deepEqual(
      state.accounts.map((a) => a.id),
      [2]
    );
  });

  /*
   * Three ways a session can end, and they are not interchangeable — which is
   * the whole point of having three.
   */
  test("signing out of this account continues as the next one", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().signOutActiveAccount();
    const state = useAuthStore.getState();
    assert.equal(state.user?.id, 1);
    assert.deepEqual(state.accounts, []);
    /* A hand-over is not “the reader signed out”, and the screens that watch
       this flag must not treat it as one. */
    assert.equal(state.isActiveLogout, false);
  });

  test("signing out of the only account leaves nobody signed in", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().signOutActiveAccount();
    const state = useAuthStore.getState();
    assert.equal(state.user, null);
    assert.deepEqual(state.accounts, []);
    assert.equal(state.isActiveLogout, true);
  });

  /*
   * The 401 path. A dead token says nothing about the other accounts, so they
   * survive — and nothing is promoted, because continuing silently as
   * somebody else would attribute the reader's next action to an account they
   * never chose.
   */
  test("a dead token ends its own session and keeps the others", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().endSession();
    const state = useAuthStore.getState();
    assert.equal(state.user, null);
    assert.deepEqual(
      state.accounts.map((a) => a.id),
      [1]
    );
    assert.equal(state.isActiveLogout, true);
  });

  test("signing out of everything clears the device", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().logout();
    const state = useAuthStore.getState();
    assert.equal(state.user, null);
    assert.deepEqual(state.accounts, []);
    assert.equal(state.isActiveLogout, true);
  });

  /* The ordering `signOutActiveAccount` promotes by: most recently used. */
  test("the account promoted is the most recently used one", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().setUser(account(3));
    useAuthStore.getState().signOutActiveAccount();
    assert.equal(useAuthStore.getState().user?.id, 2);
    useAuthStore.getState().signOutActiveAccount();
    assert.equal(useAuthStore.getState().user?.id, 1);
  });

  test("the add-another-account intent is cleared by signing in and by signing out", () => {
    useAuthStore.getState().setAddingAccount(true);
    assert.equal(useAuthStore.getState().addingAccount, true);
    useAuthStore.getState().setUser(account(1));
    assert.equal(useAuthStore.getState().addingAccount, false);

    useAuthStore.getState().setAddingAccount(true);
    useAuthStore.getState().logout();
    assert.equal(useAuthStore.getState().addingAccount, false);
  });

  /* Switching must not read as an intentional sign-out: that flag is what
     stops `RedirectIfLoggedIn` and the sign-in screen fighting each other. */
  test("switching does not set the logged-out flag", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setUser(account(2));
    useAuthStore.getState().logout();
    useAuthStore.getState().setUser(account(3));
    useAuthStore.getState().setUser(account(4));
    useAuthStore.getState().switchAccount(3);
    assert.equal(useAuthStore.getState().isActiveLogout, false);
  });
});

describe("accountLabel", () => {
  test("an organization name wins over contact details", () => {
    assert.equal(accountLabel({ id: 1, first_name: "Noor", last_name: null,
      company_name: " Fursa Team ", email: "org@e.com" }), "Fursa Team");
  });

  test("a nickname is used before email when the real name is missing", () => {
    assert.equal(accountLabel({ id: 1, first_name: null, last_name: null,
      nickname: " Volunteer ", email: "n@e.com" }), "Volunteer");
  });

  test("a full name wins", () => {
    assert.equal(
      accountLabel({ id: 1, first_name: "Noor", last_name: "Al-Sabah", email: "n@e.com" }),
      "Noor Al-Sabah"
    );
  });

  test("a first name alone is enough", () => {
    assert.equal(
      accountLabel({ id: 1, first_name: "Noor", last_name: null, email: "n@e.com" }),
      "Noor"
    );
  });

  /* Older or incomplete sessions may have no profile name. */
  test("no name falls back to the email", () => {
    assert.equal(
      accountLabel({ id: 1, first_name: null, last_name: null, email: "org@e.com" }),
      "org@e.com"
    );
  });

  test("blank strings count as absent, and the id is the last resort", () => {
    assert.equal(
      accountLabel({ id: 42, first_name: "  ", last_name: "", email: " " }),
      "#42"
    );
  });
});

describe("accountKindKey", () => {
  /*
   * Two accounts can share a name and differ only in kind — the same person
   * signed in as themselves and as the entity they run is the ordinary case
   * here — so the switcher row says which is which.
   */
  test("an entity and a volunteer are labelled apart", () => {
    assert.equal(
      accountKindKey({ user_type: "organization" }),
      "COMMON.ACCOUNT_TYPE_ORGANIZATION"
    );
    assert.equal(
      accountKindKey({ user_type: "volunteer" }),
      "COMMON.ACCOUNT_TYPE_VOLUNTEER"
    );
  });

  /* `individual` is the frontend-only alias the guards collapse to
     `volunteer`; the label follows the guard rather than disagreeing with it. */
  test("the individual alias reads as a volunteer", () => {
    assert.equal(
      accountKindKey({ user_type: "individual" }),
      "COMMON.ACCOUNT_TYPE_VOLUNTEER"
    );
  });

  /* `admin` has no screen in this app, so it gets no label rather than a
     wrong one. */
  test("an account kind with no screen gets no label", () => {
    assert.equal(accountKindKey({ user_type: "admin" }), null);
  });
});

describe("the add-another-account intent", () => {
  beforeEach(reset);

  /*
   * The bug this guards: the intent was cleared by an unmount cleanup, and
   * Strict Mode's mount → cleanup → mount made that fire the instant the
   * screen opened. Nothing clears it now except something the reader actually
   * did, so a second mount leaves it standing.
   */
  test("it survives until a sign-in or a sign-out", () => {
    useAuthStore.getState().setUser(account(1));
    useAuthStore.getState().setAddingAccount(true);

    /* Whatever else happens in between — a re-render, a remount, a profile
       patch — the intent is still there. */
    useAuthStore.getState().updateUser({ first_name: "Changed" });
    assert.equal(useAuthStore.getState().addingAccount, true);

    useAuthStore.getState().setUser(account(2));
    assert.equal(useAuthStore.getState().addingAccount, false);
  });

  test("every way out of a session clears it", () => {
    for (const end of [
      () => useAuthStore.getState().logout(),
      () => useAuthStore.getState().endSession(),
      () => useAuthStore.getState().signOutActiveAccount(),
    ]) {
      reset();
      useAuthStore.getState().setUser(account(1));
      useAuthStore.getState().setAddingAccount(true);
      end();
      assert.equal(useAuthStore.getState().addingAccount, false);
    }
  });
});
