import { create } from "zustand";
import { persist } from "zustand/middleware";

import type { ChoiceDisplay } from "@/lib/choices";

/**
 * The signed-in user, as the sign-in response delivers it.
 *
 * This is `WebsiteLoginUserResource` plus the controller-merged `auth_token`
 * (see `features/auth/authRecords.ts`), plus three fields the client caches
 * here itself. Nullability now matches the resource — `first_name`,
 * `last_name`, `email` and `manual_id` are all nullable columns, and typing
 * them `string` meant every read looked guaranteed.
 */
export interface User {
  id: number;
  first_name: string | null;
  last_name: string | null;
  company_name?: string | null;
  nickname?: string | null;
  email: string | null;
  profile_pic: string | null;
  social_media_id: string | null;
  /** `SocialMediaProvider` — exactly these two cases, or null. */
  social_media_provider: "google" | "linkedin" | null;
  /**
   * The backend's `UserType` enum is `volunteer | organization | admin`.
   *
   * `individual` is **not** one of its cases — it is a frontend-only alias
   * that `ProtectedRoute` collapses to `volunteer` before comparing, and it is
   * kept in the union because that guard and `getPublisherKind` both still
   * branch on it. Nothing in the API can produce it; `admin` can.
   */
  user_type: "individual" | "organization" | "volunteer" | "admin";
  manual_id: string | null;
  is_new_user: boolean;
  is_verified: boolean | null;
  is_banned?: boolean;
  /** Organization/team pause blocks new publication, not existing activity. */
  is_publishing_paused?: boolean;
  /**
   * "Volunteer Team" marks a team; see `lib/publishPermissions.ts`.
   *
   * **Never populated from a sign-in** — the login and social-auth responses
   * do not carry it (BE-108). Declared because `getPublisherKind` reads it and
   * will work unchanged once it arrives.
   */
  organizer_type_display?: {
    id?: number;
    value_en?: string | null;
    value_ar?: string | null;
  } | null;
  /**
   * The volunteer's gender, cached so avatars can fall back to the right
   * silhouette without a refetch. `useVolunteerAccountSubmit` writes it back
   * after a save; it used to do that through an `as any` cast because the
   * field was missing here.
   */
  gender_display?: ChoiceDisplay | null;
  /** BE-93 / BE-95 — true only once an admin approves the trainer request. */
  is_trainer?: boolean | null;
  /** BE-95 — the development types the trainer was approved for. */
  trainer_types?: Array<"course" | "workshop" | "consultation"> | null;
  /** The Sanctum token the request interceptor sends as `Authorization`. */
  auth_token: string;
  /** Absent for a volunteer — assigned inside an `if` on the resource. */
  organization?: {
    id: number;
    organization_status: "pending" | "approved" | "rejected" | (string & {});
  };
}

interface AuthState {
  user: User | null;
  /**
   * BE-129 — the sessions signed in on this device that are **not** the
   * active one, most recently used first.
   *
   * The backend needs nothing for this: a token stays valid when another
   * account signs in, so holding several and choosing which one to send is
   * entirely a client concern. There is no "my other accounts" endpoint, and
   * these are not linked to each other in any way — they are simply sessions
   * this browser happens to hold.
   *
   * `user` is still the one and only active session, so the request
   * interceptor, every guard and all ~57 `useAuthStore` readers are unchanged
   * by this.
   */
  accounts: User[];
  /**
   * BE-129 — the reader is on their way to sign a **second** account in, so
   * `RedirectIfLoggedIn` must let them reach the form instead of bouncing
   * them home.
   *
   * A store flag rather than `?add=1`, because the guard lives in
   * `(auth)/layout.tsx` and layouts receive no `searchParams`; reading the URL
   * there would mean `useSearchParams` in a client component above eight
   * prerendered routes, which the Next docs are explicit about — the tree up
   * to the nearest Suspense boundary stops being prerendered, and a static
   * page without one fails the build outright.
   *
   * Deliberately **not** persisted: it is an intent that belongs to one
   * journey, so a reload drops it and the guard goes back to bouncing.
   */
  addingAccount: boolean;
  isActiveLogout: boolean;
  profilePicTimestamp: number | null;
  // Actions
  setUser: (user: User) => void;
  /** BE-129 — make a stored session the active one. */
  switchAccount: (userId: number) => void;
  /** BE-129 — open (or abandon) the add-another-account journey. */
  setAddingAccount: (adding: boolean) => void;
  /**
   * BE-129 — sign out of **this** account and continue as the next one.
   *
   * What the reader asked for by pressing «تسجيل الخروج» while holding more
   * than one session: the account they are looking at ends, and the most
   * recently used of the others takes over. With no others it is an ordinary
   * sign-out and leaves nobody signed in.
   */
  signOutActiveAccount: () => void;
  /**
   * BE-129 — the active session ends and **nothing is promoted**.
   *
   * For a token that died under us (the 401 interceptor), where promoting
   * would silently continue as somebody else: the next thing the reader did
   * — a comment, a registration, a withdrawal — would be done as an account
   * they never chose. The other sessions are kept, and the sign-in screen
   * offers them.
   */
  endSession: () => void;
  /** Sign out of every account on this device. */
  logout: () => void;
  updateProfilePic: (url: string) => void;
  updateUser: (data: Partial<User>) => void;
  resetLogoutFlag: () => void;
}

/** Everything but `userId`, keeping order. */
const withoutAccount = (accounts: User[], userId: number | undefined) =>
  accounts.filter((account) => account.id !== userId);

/**
 * A voluntary team signs in with `user_type: "voluntary_team"` (its own
 * `UserType` case since team sign-up, `WebsiteLoginUserResource`), but every
 * guard and organizer check here compares against `"organization"`, and
 * `getPublisherKind` tells a team apart by its «Volunteer Team» organizer
 * type, which the team profile always carries. Without this a team was
 * treated as an individual: no publishing (p.41) and no organizer routes.
 */
export function normalizeSessionUser<T extends { user_type?: unknown }>(user: T): T {
  return user.user_type === "voluntary_team" ? { ...user, user_type: "organization" } : user;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set, get) => ({
      user: null,
      accounts: [],
      addingAccount: false,
      isActiveLogout: false,
      profilePicTimestamp: null,

      /*
       * BE-129 — signing in while already signed in backgrounds the previous
       * session instead of discarding it.
       *
       * Keyed on `id`, so signing in again as the same account replaces that
       * session rather than stacking a second copy of it with a stale token.
       * `profilePicTimestamp` is dropped because it is a cache-buster for the
       * *active* avatar, and the avatar is about to change.
       */
      setUser: (signedIn) =>
        set((state) => {
          const user = normalizeSessionUser(signedIn);
          return {
          user,
          accounts:
            state.user && state.user.id !== user.id
              ? [state.user, ...withoutAccount(state.accounts, state.user.id)].filter(
                  (account) => account.id !== user.id
                )
              : withoutAccount(state.accounts, user.id),
          addingAccount: false,
          isActiveLogout: false,
          profilePicTimestamp: null,
          };
        }),

      setAddingAccount: (adding) => set({ addingAccount: adding }),

      switchAccount: (userId) =>
        set((state) => {
          const next = state.accounts.find((account) => account.id === userId);
          /* Unknown id: leave the session alone rather than signing anyone
             out. It can happen if a stored account was cleared in another tab
             between the menu rendering and the click. */
          if (!next) return state;
          return {
            user: next,
            accounts: state.user
              ? [state.user, ...withoutAccount(state.accounts, userId)]
              : withoutAccount(state.accounts, userId),
            isActiveLogout: false,
            profilePicTimestamp: null,
          };
        }),

      signOutActiveAccount: () =>
        set((state) => {
          const [next, ...rest] = state.accounts;
          return {
            user: next ?? null,
            accounts: next ? rest : [],
            addingAccount: false,
            /* Only a sign-out that leaves nobody behind is “the reader signed
               out”. Handing over to another account is a switch, and the
               screens that watch this flag must not treat it as one. */
            isActiveLogout: !next,
            profilePicTimestamp: null,
          };
        }),

      endSession: () =>
        set((state) => ({
          user: null,
          accounts: state.accounts,
          addingAccount: false,
          isActiveLogout: true,
          profilePicTimestamp: null,
        })),

      /*
       * Every session on this device, which is what «تسجيل الخروج من كل
       * الحسابات» means on a shared computer: nothing of anyone's is left
       * sitting in `localStorage`.
       */
      logout: () =>
        set({
          user: null,
          accounts: [],
          addingAccount: false,
          isActiveLogout: true,
          profilePicTimestamp: null,
        }),

      updateProfilePic: (url) => {
        const user = get().user;
        if (user) {
          set({ user: { ...user, profile_pic: url }, profilePicTimestamp: Date.now() });
        }
      },

      updateUser: (data) => {
        const user = get().user;
        if (user) {
          set({ user: { ...user, ...data } });
        }
      },

      resetLogoutFlag: () => set({ isActiveLogout: false }),
    }),
    {
      name: "fursa-auth",
      /* `accounts` is persisted too, or switching would only survive until the
         next reload — which is the whole point of holding them. */
      partialize: (state) => ({ user: state.user, accounts: state.accounts }),
      /* A team session stored before `normalizeSessionUser` existed. */
      merge: (persisted, current) => {
        const saved = (persisted ?? {}) as Partial<AuthState>;
        return {
          ...current,
          ...saved,
          user: saved.user ? normalizeSessionUser(saved.user) : current.user,
          accounts: (saved.accounts ?? current.accounts).map(normalizeSessionUser),
        };
      },
    }
  )
);

