export const initialAccountsState = { pending: false, pendingAccountId: "", error: "" };

const safeAccountErrors = new Set([
  "account_config_write_failed",
  "account_home_create_failed",
  "account_login_rate_limited",
  "account_login_start_failed",
  "last_visible_account"
]);

export function accountMutationError(error, fallback) {
  if (safeAccountErrors.has(error?.message)) return error.message;
  return fallback;
}

export function reduceAccountsState(state, action) {
  if (action.type === "mutation.started") {
    return { pending: true, pendingAccountId: action.accountId ?? "", error: "" };
  }
  if (action.type === "mutation.failed") {
    return { pending: false, pendingAccountId: "", error: action.error };
  }
  if (action.type === "mutation.completed") return initialAccountsState;
  return state;
}
