import type { User } from "@/store/authStore";

/** The `GET /account/` keys that decide what the signed-in account may publish. */
export interface AccountSessionFlags {
  /** Whose `/account/` this is — compared with the session before anything is copied. */
  id?: number | string | null;
  is_trainer?: boolean | null;
  trainer_types?: string[] | null;
  /** BE-186 — what actually grants publishing; preferred over `trainer_types`. */
  approved_trainer_types?: string[] | null;
  is_publishing_paused?: boolean | null;
}

type TrainerSlug = NonNullable<User["trainer_types"]>[number];

const sameList = (a: readonly string[], b: readonly string[]) =>
  a.length === b.length && a.every((value, index) => value === b[index]);

/**
 * The stored session's publishing flags, refreshed from `/account/`.
 *
 * The session is the sign-in payload, frozen at sign-in. An admin approving a
 * trainer request (PDF p.10) or pausing / resuming an organization's
 * publishing (A2) changed nothing on this device until the next sign-in: an
 * approved trainer was never offered the publish menu, and an organization
 * whose pause was lifted stayed locked out of publishing.
 *
 * Returns only the keys that differ — `null` when nothing does — so the caller
 * writes to the store only on a real change. A key the response lacks is left
 * alone rather than cleared. A response for another account (a cached
 * `["account-info"]` left by a session that ended without a reload) is
 * ignored, so one account's trainer or pause flags never land on another.
 */
export function sessionFlagsUpdate(
  user: Pick<User, "is_trainer" | "trainer_types" | "is_publishing_paused"> & { id?: number | null } | null | undefined,
  account: AccountSessionFlags | null | undefined
): Partial<User> | null {
  if (!user || !account) return null;
  if (account.id != null && user.id != null && String(account.id) !== String(user.id)) return null;
  const update: Partial<User> = {};

  if (typeof account.is_trainer === "boolean" && account.is_trainer !== (user.is_trainer === true)) {
    update.is_trainer = account.is_trainer;
  }
  const types = account.approved_trainer_types ?? account.trainer_types;
  if (Array.isArray(types) && !sameList(types, user.trainer_types ?? [])) {
    update.trainer_types = types as TrainerSlug[];
  }
  if (
    typeof account.is_publishing_paused === "boolean" &&
    account.is_publishing_paused !== (user.is_publishing_paused === true)
  ) {
    update.is_publishing_paused = account.is_publishing_paused;
  }

  return Object.keys(update).length > 0 ? update : null;
}
